From 0a0baee45ebcff44635907d457c4ff6810b09c87 Mon Sep 17 00:00:00 2001 From: Alex Rudyy Date: Wed, 15 Apr 2015 09:47:28 +0000 Subject: QPID-6481: Move java source tree to top level git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1673693 13f79535-47bb-0310-9956-ffa450edef68 --- qpid/java/broker-plugins/access-control/pom.xml | 91 - .../server/security/access/config/AclAction.java | 102 - .../security/access/config/AclRulePredicates.java | 104 - .../qpid/server/security/access/config/Action.java | 171 - .../security/access/config/ClientAction.java | 88 - .../security/access/config/ConfigurationFile.java | 39 - .../security/access/config/PlainConfiguration.java | 327 -- .../qpid/server/security/access/config/Rule.java | 172 - .../server/security/access/config/RuleSet.java | 447 --- .../firewall/AccessControlFirewallException.java | 47 - .../security/access/firewall/FirewallRule.java | 26 - .../access/firewall/FirewallRuleFactory.java | 33 - .../access/firewall/HostnameFirewallRule.java | 157 - .../security/access/firewall/InetNetwork.java | 159 - .../access/firewall/NetworkFirewallRule.java | 118 - .../plugins/ACLFileAccessControlProvider.java | 32 - .../plugins/ACLFileAccessControlProviderImpl.java | 234 -- .../access/plugins/DefaultAccessControl.java | 202 -- .../access-control/src/main/resources/acl.xsd | 29 - .../security/access/config/AclActionTest.java | 66 - .../access/config/AclRulePredicatesTest.java | 87 - .../server/security/access/config/ActionTest.java | 95 - .../security/access/config/ClientActionTest.java | 79 - .../access/config/PlainConfigurationTest.java | 446 --- .../server/security/access/config/RuleTest.java | 53 - .../access/firewall/HostnameFirewallRuleTest.java | 99 - .../access/firewall/NetworkFirewallRuleTest.java | 115 - .../ACLFileAccessControlProviderFactoryTest.java | 118 - .../ACLFileAccessControlProviderImplTest.java | 81 - .../access/plugins/DefaultAccessControlTest.java | 471 --- .../security/access/plugins/RuleSetTest.java | 468 --- .../java/broker-plugins/amqp-0-10-protocol/pom.xml | 79 - .../server/protocol/v0_10/ConsumerTarget_0_10.java | 669 ---- .../server/protocol/v0_10/CreditCreditManager.java | 162 - .../ExplicitAcceptDispositionChangeListener.java | 92 - .../protocol/v0_10/FlowCreditManager_0_10.java | 30 - .../ImplicitAcceptDispositionChangeListener.java | 90 - .../v0_10/MessageAcceptCompletionListener.java | 68 - .../v0_10/MessageConverter_Internal_to_v0_10.java | 147 - .../protocol/v0_10/MessageConverter_v0_10.java | 223 -- .../v0_10/MessageConverter_v0_10_to_Internal.java | 266 -- .../protocol/v0_10/MessageMetaDataType_0_10.java | 70 - .../protocol/v0_10/MessageMetaData_0_10.java | 256 -- .../protocol/v0_10/MessageTransferHeader.java | 171 - .../protocol/v0_10/MessageTransferMessage.java | 83 - .../protocol/v0_10/ProtocolEngineCreator_0_10.java | 108 - .../server/protocol/v0_10/ProtocolEngine_0_10.java | 338 -- .../server/protocol/v0_10/ServerAssembler.java | 57 - .../server/protocol/v0_10/ServerConnection.java | 770 ---- .../protocol/v0_10/ServerConnectionDelegate.java | 443 --- .../server/protocol/v0_10/ServerDisassembler.java | 248 -- .../qpid/server/protocol/v0_10/ServerEncoder.java | 371 -- .../qpid/server/protocol/v0_10/ServerSession.java | 1221 ------- .../protocol/v0_10/ServerSessionDelegate.java | 1656 --------- .../server/protocol/v0_10/WindowCreditManager.java | 201 -- .../server/protocol/v0_10/ServerSessionTest.java | 135 - .../protocol/v0_10/WindowCreditManagerTest.java | 92 - qpid/java/broker-plugins/amqp-0-8-protocol/pom.xml | 77 - .../qpid/server/protocol/v0_8/AMQChannel.java | 3670 -------------------- .../qpid/server/protocol/v0_8/AMQMessage.java | 108 - .../protocol/v0_8/AMQNoMethodHandlerException.java | 42 - .../server/protocol/v0_8/AMQProtocolEngine.java | 2033 ----------- .../qpid/server/protocol/v0_8/BrokerDecoder.java | 118 - .../server/protocol/v0_8/ClientDeliveryMethod.java | 31 - .../protocol/v0_8/ConsumerTagInUseException.java | 29 - .../server/protocol/v0_8/ConsumerTarget_0_8.java | 565 --- .../protocol/v0_8/ExtractResendAndRequeue.java | 79 - .../qpid/server/protocol/v0_8/IncomingMessage.java | 107 - .../v0_8/MessageConverter_Internal_to_v0_8.java | 244 -- .../v0_8/MessageConverter_v0_8_to_Internal.java | 358 -- .../qpid/server/protocol/v0_8/MessageMetaData.java | 296 -- .../protocol/v0_8/MessageMetaDataType_0_8.java | 70 - .../protocol/v0_8/MessageOnlyCreditManager.java | 73 - .../server/protocol/v0_8/NoAckCreditManager.java | 56 - .../server/protocol/v0_8/Pre0_10CreditManager.java | 190 - .../protocol/v0_8/ProtocolEngineCreator_0_8.java | 82 - .../protocol/v0_8/ProtocolEngineCreator_0_9.java | 82 - .../protocol/v0_8/ProtocolEngineCreator_0_9_1.java | 84 - .../protocol/v0_8/ProtocolOutputConverter.java | 55 - .../protocol/v0_8/ProtocolOutputConverterImpl.java | 543 --- .../server/protocol/v0_8/RecordDeliveryMethod.java | 29 - .../protocol/v0_8/UnacknowledgedMessageMap.java | 70 - .../v0_8/UnacknowledgedMessageMapImpl.java | 178 - .../protocol/v0_8/UnexpectedMethodException.java | 36 - .../qpid/server/protocol/v0_8/AMQChannelTest.java | 180 - .../protocol/v0_8/AMQProtocolEngineTest.java | 106 - .../apache/qpid/server/protocol/v0_8/AckTest.java | 353 -- .../qpid/server/protocol/v0_8/AcknowledgeTest.java | 185 - .../server/protocol/v0_8/BrokerTestHelper_0_8.java | 109 - .../protocol/v0_8/ExtractResendAndRequeueTest.java | 184 - .../protocol/v0_8/InternalTestProtocolSession.java | 357 -- .../protocol/v0_8/LimitlessCreditManager.java | 47 - .../qpid/server/protocol/v0_8/MaxChannelsTest.java | 72 - .../qpid/server/protocol/v0_8/MockAMQMessage.java | 40 - .../server/protocol/v0_8/MockStoredMessage.java | 127 - .../protocol/v0_8/QueueBrowserUsesNoAckTest.java | 150 - .../protocol/v0_8/ReferenceCountingTest.java | 169 - .../v0_8/UnacknowledgedMessageMapTest.java | 84 - qpid/java/broker-plugins/amqp-1-0-protocol/pom.xml | 64 - .../qpid/server/protocol/v1_0/Connection_1_0.java | 553 --- .../server/protocol/v1_0/ConsumerTarget_1_0.java | 550 --- .../qpid/server/protocol/v1_0/Destination.java | 28 - .../server/protocol/v1_0/ExchangeDestination.java | 158 - .../apache/qpid/server/protocol/v1_0/Link_1_0.java | 28 - .../v1_0/MessageConverter_Internal_to_v1_0.java | 143 - .../protocol/v1_0/MessageConverter_from_1_0.java | 343 -- .../protocol/v1_0/MessageConverter_to_1_0.java | 303 -- .../v1_0/MessageConverter_v1_0_to_Internal.java | 67 - .../protocol/v1_0/MessageMetaDataType_1_0.java | 70 - .../server/protocol/v1_0/MessageMetaData_1_0.java | 599 ---- .../protocol/v1_0/MessageSourceDestination.java | 56 - .../qpid/server/protocol/v1_0/Message_1_0.java | 142 - .../protocol/v1_0/NodeReceivingDestination.java | 129 - .../v1_0/ProtocolEngineCreator_1_0_0_SASL.java | 82 - .../protocol/v1_0/ProtocolEngine_1_0_0_SASL.java | 631 ---- .../server/protocol/v1_0/QueueDestination.java | 87 - .../server/protocol/v1_0/ReceivingDestination.java | 35 - .../protocol/v1_0/ReceivingLinkAttachment.java | 71 - .../server/protocol/v1_0/ReceivingLink_1_0.java | 310 -- .../server/protocol/v1_0/SendingDestination.java | 27 - .../protocol/v1_0/SendingLinkAttachment.java | 64 - .../qpid/server/protocol/v1_0/SendingLink_1_0.java | 719 ---- .../qpid/server/protocol/v1_0/Session_1_0.java | 962 ----- .../protocol/v1_0/TxnCoordinatorLink_1_0.java | 208 -- .../qpid/server/protocol/v1_0/UnsettledAction.java | 28 - .../amqp-msg-conv-0-10-to-1-0/pom.xml | 75 - .../v0_10_v1_0/MessageConverter_0_10_to_1_0.java | 154 - .../v0_10_v1_0/MessageConverter_1_0_to_v0_10.java | 198 -- .../amqp-msg-conv-0-8-to-0-10/pom.xml | 69 - .../v0_8_v0_10/MessageConverter_0_10_to_0_8.java | 261 -- .../v0_8_v0_10/MessageConverter_0_8_to_0_10.java | 228 -- .../amqp-msg-conv-0-8-to-1-0/pom.xml | 75 - .../v0_8_v1_0/MessageConverter_0_8_to_1_0.java | 176 - .../v0_8_v1_0/MessageConverter_1_0_to_v0_8.java | 183 - qpid/java/broker-plugins/derby-store/pom.xml | 89 - .../store/derby/AbstractDerbyMessageStore.java | 331 -- .../store/derby/DerbyConfigurationStore.java | 242 -- .../qpid/server/store/derby/DerbyMessageStore.java | 118 - .../qpid/server/store/derby/DerbySystemConfig.java | 39 - .../server/store/derby/DerbySystemConfigImpl.java | 81 - .../apache/qpid/server/store/derby/DerbyUtils.java | 234 -- .../server/virtualhost/derby/DerbyVirtualHost.java | 40 - .../virtualhost/derby/DerbyVirtualHostImpl.java | 89 - .../derby/DerbyVirtualHostNode.java | 31 - .../derby/DerbyVirtualHostNodeImpl.java | 94 - .../js/qpid/management/virtualhost/derby/add.js | 45 - .../js/qpid/management/virtualhost/derby/edit.js | 34 - .../js/qpid/management/virtualhost/derby/show.js | 38 - .../qpid/management/virtualhostnode/derby/add.js | 41 - .../qpid/management/virtualhostnode/derby/edit.js | 33 - .../qpid/management/virtualhostnode/derby/show.js | 38 - .../java/resources/virtualhostnode/derby/add.html | 35 - .../java/resources/virtualhostnode/derby/show.html | 21 - .../derby/DerbyMessageStoreConfigurationTest.java | 49 - .../derby/DerbyMessageStoreQuotaEventsTest.java | 76 - .../server/store/derby/DerbyMessageStoreTest.java | 96 - .../derby/DerbyVirtualHostNodeTest.java | 175 - .../java/broker-plugins/jdbc-provider-bone/pom.xml | 83 - .../jdbc/bonecp/BoneCPConnectionProvider.java | 89 - .../bonecp/BoneCPConnectionProviderFactory.java | 61 - .../js/qpid/management/store/pool/bonecp/add.js | 44 - .../js/qpid/management/store/pool/bonecp/edit.js | 33 - .../js/qpid/management/store/pool/bonecp/show.js | 66 - .../java/resources/store/pool/bonecp/show.html | 37 - qpid/java/broker-plugins/jdbc-store/pom.xml | 91 - .../store/jdbc/DefaultConnectionProvider.java | 57 - .../jdbc/DefaultConnectionProviderFactory.java | 53 - .../jdbc/GenericAbstractJDBCMessageStore.java | 160 - .../store/jdbc/GenericJDBCConfigurationStore.java | 329 -- .../server/store/jdbc/GenericJDBCMessageStore.java | 199 -- .../apache/qpid/server/store/jdbc/JDBCDetails.java | 370 -- .../qpid/server/store/jdbc/JDBCSettings.java | 33 - .../qpid/server/store/jdbc/JDBCSystemConfig.java | 39 - .../server/store/jdbc/JDBCSystemConfigImpl.java | 89 - .../server/virtualhost/jdbc/JDBCVirtualHost.java | 43 - .../virtualhost/jdbc/JDBCVirtualHostImpl.java | 95 - .../virtualhostnode/jdbc/JDBCVirtualHostNode.java | 41 - .../jdbc/JDBCVirtualHostNodeImpl.java | 109 - .../js/qpid/management/store/pool/none/add.js | 41 - .../js/qpid/management/store/pool/none/edit.js | 26 - .../js/qpid/management/store/pool/none/show.js | 33 - .../js/qpid/management/virtualhost/jdbc/add.js | 82 - .../js/qpid/management/virtualhost/jdbc/edit.js | 82 - .../js/qpid/management/virtualhost/jdbc/show.js | 64 - .../js/qpid/management/virtualhostnode/jdbc/add.js | 85 - .../qpid/management/virtualhostnode/jdbc/edit.js | 86 - .../qpid/management/virtualhostnode/jdbc/show.js | 68 - .../main/java/resources/virtualhost/jdbc/add.html | 76 - .../main/java/resources/virtualhost/jdbc/edit.html | 78 - .../resources/virtualhost/store/pool/none/add.html | 17 - .../java/resources/virtualhostnode/jdbc/add.html | 77 - .../java/resources/virtualhostnode/jdbc/edit.html | 77 - .../java/resources/virtualhostnode/jdbc/show.html | 34 - .../virtualhostnode/store/pool/none/add.html | 17 - .../qpid/server/store/jdbc/JDBCDetailsTest.java | 94 - .../server/store/jdbc/JDBCMessageStoreTest.java | 158 - qpid/java/broker-plugins/management-amqp/pom.xml | 53 - .../server/management/amqp/ManagedEntityType.java | 73 - .../server/management/amqp/ManagementNode.java | 1449 -------- .../management/amqp/ManagementNodeConsumer.java | 240 -- .../management/amqp/ManagementNodeCreator.java | 41 - .../server/management/amqp/ManagementResponse.java | 250 -- qpid/java/broker-plugins/management-http/pom.xml | 140 - .../main/appended-resources/META-INF/LICENSE.vm | 33 - .../qpid/server/management/plugin/DojoHelper.java | 119 - .../server/management/plugin/HttpManagement.java | 613 ---- .../plugin/HttpManagementConfiguration.java | 82 - .../management/plugin/HttpManagementUtil.java | 270 -- .../connector/TcpAndSslSelectChannelConnector.java | 378 -- .../filter/ForbiddingAuthorisationFilter.java | 93 - .../plugin/filter/ForbiddingTraceFilter.java | 68 - .../filter/RedirectingAuthorisationFilter.java | 83 - .../management/plugin/log/LogFileDetails.java | 78 - .../management/plugin/log/LogFileHelper.java | 243 -- .../plugin/report/QueueBinaryReport.java | 28 - .../management/plugin/report/QueueReport.java | 161 - .../management/plugin/report/QueueTextReport.java | 28 - .../management/plugin/report/ReportRunner.java | 408 --- .../plugin/report/ReportableMessage.java | 42 - .../plugin/report/ReportableMessageHeader.java | 58 - .../plugin/servlet/DefinedFileServlet.java | 84 - .../management/plugin/servlet/FileServlet.java | 127 - .../management/plugin/servlet/LogFileServlet.java | 107 - .../plugin/servlet/ServletConnectionPrincipal.java | 84 - .../plugin/servlet/rest/AbstractServlet.java | 291 -- .../management/plugin/servlet/rest/Action.java | 32 - .../plugin/servlet/rest/ApiDocsServlet.java | 423 --- .../rest/ConfiguredObjectToMapConverter.java | 314 -- .../plugin/servlet/rest/HelperServlet.java | 126 - .../plugin/servlet/rest/KeyComparator.java | 53 - .../plugin/servlet/rest/LogFileListingServlet.java | 68 - .../plugin/servlet/rest/LogRecordsServlet.java | 104 - .../rest/LoggedOnUserPreferencesServlet.java | 138 - .../plugin/servlet/rest/LogoutServlet.java | 65 - .../plugin/servlet/rest/MapComparator.java | 74 - .../plugin/servlet/rest/MessageContentServlet.java | 174 - .../plugin/servlet/rest/MessageServlet.java | 568 --- .../plugin/servlet/rest/MetaDataServlet.java | 200 -- .../servlet/rest/PluginClassProviderAction.java | 60 - .../plugin/servlet/rest/QueueReportServlet.java | 103 - .../plugin/servlet/rest/RestServlet.java | 774 ----- .../plugin/servlet/rest/SaslServlet.java | 319 -- .../plugin/servlet/rest/StructureServlet.java | 100 - .../servlet/rest/UserPreferencesServlet.java | 237 -- .../action/AbstractSpecialisedAttributeLister.java | 78 - .../ListAccessControlProviderAttributes.java | 38 - .../servlet/rest/action/ListBrokerAttribute.java | 52 - .../rest/action/ListGroupProviderAttributes.java | 38 - .../plugin/servlet/rest/action/ListTimeZones.java | 117 - .../plugin/session/LoginLogoutReporter.java | 110 - .../accesscontrolprovider/aclfile/add.html | 64 - .../accesscontrolprovider/showAclFile.html | 27 - .../java/resources/addAccessControlProvider.html | 66 - .../java/resources/addAuthenticationProvider.html | 64 - .../src/main/java/resources/addBinding.html | 64 - .../src/main/java/resources/addExchange.html | 74 - .../src/main/java/resources/addGroupProvider.html | 66 - .../src/main/java/resources/addPort.html | 260 -- .../java/resources/addPreferencesProvider.html | 28 - .../src/main/java/resources/addQueue.html | 344 -- .../src/main/java/resources/addStore.html | 66 - .../addVirtualHostNodeAndVirtualHost.html | 136 - .../resources/authenticationprovider/addUser.html | 42 - .../authenticationprovider/external/add.html | 30 - .../authenticationprovider/external/show.html | 26 - .../authenticationprovider/filebased/add.html | 31 - .../authenticationprovider/filebased/show.html | 26 - .../authenticationprovider/setPassword.html | 42 - ...showPrincipalDatabaseAuthenticationManager.html | 27 - .../authenticationprovider/simpleldap/add.html | 133 - .../authenticationprovider/simpleldap/show.html | 58 - .../resources/common/ContextVariablesEditor.html | 35 - .../main/java/resources/common/ResourceWidget.html | 48 - .../java/resources/common/TimeZoneSelector.html | 66 - .../src/main/java/resources/css/apidocs.css | 86 - .../src/main/java/resources/css/common.css | 339 -- .../src/main/java/resources/editBroker.html | 119 - .../src/main/java/resources/editQueue.html | 300 -- .../src/main/java/resources/editVirtualHost.html | 137 - .../main/java/resources/editVirtualHostNode.html | 56 - .../src/main/java/resources/footer.html | 28 - .../java/resources/grid/showColumnDefDialog.html | 32 - .../resources/grid/showRowNumberLimitDialog.html | 33 - .../main/java/resources/group/addGroupMember.html | 38 - .../src/main/java/resources/group/showGroup.html | 32 - .../java/resources/groupprovider/addGroup.html | 39 - .../resources/groupprovider/groupfile/add.html | 37 - .../resources/groupprovider/groupfile/show.html | 25 - .../showGroupManagingGroupProvider.html | 30 - .../main/java/resources/images/auto-refresh.png | Bin 535 -> 0 bytes .../src/main/java/resources/images/download.png | Bin 803 -> 0 bytes .../src/main/java/resources/images/gear.png | Bin 3512 -> 0 bytes .../src/main/java/resources/images/help.png | Bin 932 -> 0 bytes .../src/main/java/resources/images/log-viewer.png | Bin 719 -> 0 bytes .../src/main/java/resources/images/qpid-logo.png | Bin 6798 -> 0 bytes .../src/main/java/resources/images/refresh.png | Bin 468 -> 0 bytes .../src/main/java/resources/index.html | 137 - .../main/java/resources/js/crypto-js/README.txt | 8 - .../java/resources/js/crypto-js/enc-base64-min.js | 8 - .../main/java/resources/js/crypto-js/hmac-sha1.js | 17 - .../java/resources/js/crypto-js/hmac-sha256.js | 18 - .../resources/js/qpid/authorization/checkUser.js | 45 - .../java/resources/js/qpid/authorization/sasl.js | 351 -- .../java/resources/js/qpid/common/ConsoleHelper.js | 72 - .../js/qpid/common/ContextVariablesEditor.js | 558 --- .../resources/js/qpid/common/FormWidgetMixin.js | 102 - .../resources/js/qpid/common/ResourceWidget.js | 196 -- .../resources/js/qpid/common/TimeZoneSelector.js | 217 -- .../resources/js/qpid/common/UpdatableStore.js | 189 - .../main/java/resources/js/qpid/common/footer.js | 30 - .../java/resources/js/qpid/common/formatter.js | 99 - .../js/qpid/common/grid/ColumnDefDialog.js | 145 - .../js/qpid/common/grid/EnhancedFilter.js | 230 -- .../js/qpid/common/grid/EnhancedFilterTools.js | 310 -- .../resources/js/qpid/common/grid/FilterSummary.js | 173 - .../resources/js/qpid/common/grid/GridUpdater.js | 297 -- .../js/qpid/common/grid/RowNumberLimitDialog.js | 102 - .../resources/js/qpid/common/grid/UpdatableGrid.js | 56 - .../main/java/resources/js/qpid/common/metadata.js | 89 - .../java/resources/js/qpid/common/properties.js | 26 - .../main/java/resources/js/qpid/common/timezone.js | 95 - .../main/java/resources/js/qpid/common/updater.js | 65 - .../src/main/java/resources/js/qpid/common/util.js | 842 ----- .../resources/js/qpid/common/widgetconfigurer.js | 152 - .../js/qpid/management/AccessControlProvider.js | 132 - .../js/qpid/management/AuthenticationProvider.js | 243 -- .../java/resources/js/qpid/management/Broker.js | 715 ---- .../resources/js/qpid/management/Connection.js | 243 -- .../java/resources/js/qpid/management/Exchange.js | 301 -- .../resources/js/qpid/management/GroupProvider.js | 199 -- .../java/resources/js/qpid/management/KeyStore.js | 172 - .../java/resources/js/qpid/management/Plugin.js | 94 - .../main/java/resources/js/qpid/management/Port.js | 220 -- .../resources/js/qpid/management/Preferences.js | 281 -- .../js/qpid/management/PreferencesProvider.js | 187 - .../java/resources/js/qpid/management/Queue.js | 566 --- .../resources/js/qpid/management/TrustStore.js | 169 - .../js/qpid/management/UserPreferences.js | 313 -- .../resources/js/qpid/management/VirtualHost.js | 483 --- .../js/qpid/management/VirtualHostNode.js | 220 -- .../management/accesscontrolprovider/AclFile.js | 96 - .../accesscontrolprovider/aclfile/add.js | 125 - .../js/qpid/management/addAccessControlProvider.js | 149 - .../qpid/management/addAuthenticationProvider.js | 221 -- .../resources/js/qpid/management/addBinding.js | 423 --- .../resources/js/qpid/management/addExchange.js | 135 - .../js/qpid/management/addGroupProvider.js | 178 - .../java/resources/js/qpid/management/addPort.js | 476 --- .../js/qpid/management/addPreferencesProvider.js | 94 - .../java/resources/js/qpid/management/addQueue.js | 185 - .../java/resources/js/qpid/management/addStore.js | 189 - .../management/addVirtualHostNodeAndVirtualHost.js | 409 --- .../PrincipalDatabaseAuthenticationManager.js | 279 -- .../authenticationprovider/anonymous/add.js | 21 - .../authenticationprovider/anonymous/show.js | 35 - .../base64md5passwordfile/add.js | 40 - .../base64md5passwordfile/show.js | 38 - .../authenticationprovider/external/add.js | 40 - .../authenticationprovider/external/show.js | 38 - .../authenticationprovider/kerberos/add.js | 22 - .../authenticationprovider/kerberos/show.js | 35 - .../management/authenticationprovider/md5/add.js | 21 - .../management/authenticationprovider/md5/show.js | 35 - .../management/authenticationprovider/plain/add.js | 21 - .../authenticationprovider/plain/show.js | 35 - .../plainpasswordfile/add.js | 40 - .../plainpasswordfile/show.js | 38 - .../authenticationprovider/scram-sha-1/add.js | 21 - .../authenticationprovider/scram-sha-1/show.js | 35 - .../authenticationprovider/scram-sha-256/add.js | 21 - .../authenticationprovider/scram-sha-256/show.js | 35 - .../authenticationprovider/simpleldap/add.js | 82 - .../authenticationprovider/simpleldap/show.js | 43 - .../resources/js/qpid/management/controller.js | 140 - .../resources/js/qpid/management/editBroker.js | 188 - .../java/resources/js/qpid/management/editQueue.js | 219 -- .../js/qpid/management/editVirtualHost.js | 207 -- .../js/qpid/management/editVirtualHostNode.js | 177 - .../resources/js/qpid/management/group/Group.js | 204 -- .../js/qpid/management/group/addGroupMember.js | 97 - .../groupprovider/GroupManagingGroupProvider.js | 196 -- .../qpid/management/groupprovider/groupfile/add.js | 40 - .../management/groupprovider/groupfile/show.js | 37 - .../groupprovider/managedgroupprovider/add.js | 26 - .../groupprovider/managedgroupprovider/show.js | 35 - .../qpid/management/logs/LogFileDownloadDialog.js | 178 - .../resources/js/qpid/management/logs/LogViewer.js | 228 -- .../js/qpid/management/moveCopyMessages.js | 137 - .../js/qpid/management/plugin/managementhttp.js | 185 - .../js/qpid/management/plugin/managementjmx.js | 121 - .../preferencesprovider/PreferencesProviderForm.js | 198 -- .../filesystempreferences/add.js | 38 - .../filesystempreferences/show.js | 48 - .../resources/js/qpid/management/showMessage.js | 142 - .../js/qpid/management/store/filekeystore/add.js | 101 - .../js/qpid/management/store/filekeystore/show.js | 42 - .../js/qpid/management/store/filetruststore/add.js | 96 - .../qpid/management/store/filetruststore/show.js | 42 - .../qpid/management/store/nonjavakeystore/add.js | 102 - .../qpid/management/store/nonjavakeystore/show.js | 61 - .../qpid/management/store/nonjavatruststore/add.js | 94 - .../management/store/nonjavatruststore/show.js | 70 - .../java/resources/js/qpid/management/treeView.js | 365 -- .../management/virtualhost/providedstore/add.js | 52 - .../management/virtualhost/providedstore/edit.js | 35 - .../management/virtualhost/providedstore/show.js | 37 - .../js/qpid/management/virtualhostnode/json/add.js | 41 - .../qpid/management/virtualhostnode/json/edit.js | 33 - .../qpid/management/virtualhostnode/json/show.js | 39 - .../src/main/java/resources/login.html | 120 - .../resources/logs/showLogFileDownloadDialog.html | 33 - .../main/java/resources/logs/showLogViewer.html | 29 - .../src/main/java/resources/moveCopyMessages.html | 36 - .../java/resources/plugin/showManagementHttp.html | 52 - .../java/resources/plugin/showManagementJmx.html | 32 - .../filesystempreferences/add.html | 37 - .../filesystempreferences/show.html | 21 - .../preferencesProviderForm.html | 62 - .../java/resources/showAccessControlProvider.html | 44 - .../src/main/java/resources/showAuthProvider.html | 45 - .../src/main/java/resources/showBroker.html | 136 - .../src/main/java/resources/showConnection.html | 96 - .../src/main/java/resources/showExchange.html | 83 - .../src/main/java/resources/showGroupProvider.html | 45 - .../src/main/java/resources/showMessage.html | 81 - .../src/main/java/resources/showPlugin.html | 33 - .../src/main/java/resources/showPort.html | 102 - .../src/main/java/resources/showPreferences.html | 79 - .../java/resources/showPreferencesProvider.html | 38 - .../src/main/java/resources/showQueue.html | 215 -- .../src/main/java/resources/showStore.html | 46 - .../src/main/java/resources/showVirtualHost.html | 140 - .../main/java/resources/showVirtualHostNode.html | 52 - .../java/resources/store/filekeystore/add.html | 86 - .../java/resources/store/filekeystore/show.html | 39 - .../java/resources/store/filetruststore/add.html | 84 - .../java/resources/store/filetruststore/show.html | 39 - .../java/resources/store/nonjavakeystore/add.html | 66 - .../java/resources/store/nonjavakeystore/show.html | 47 - .../resources/store/nonjavatruststore/add.html | 38 - .../resources/store/nonjavatruststore/show.html | 31 - .../src/main/java/resources/strings.html | 21 - .../resources/virtualhost/providedstore/add.html | 51 - .../resources/virtualhost/providedstore/edit.html | 53 - .../resources/virtualhost/providedstore/show.html | 30 - .../resources/virtualhost/sizemonitoring/add.html | 61 - .../resources/virtualhost/sizemonitoring/edit.html | 65 - .../resources/virtualhost/sizemonitoring/show.html | 34 - .../resources/virtualhostnode/filebased/edit.html | 36 - .../java/resources/virtualhostnode/json/add.html | 34 - .../java/resources/virtualhostnode/json/show.html | 21 - .../src/main/resources-maven/dojoconfig.properties | 25 - .../management/plugin/HttpManagementTest.java | 117 - .../management/plugin/log/LogFileHelperTest.java | 339 -- .../management/plugin/report/ReportRunnerTest.java | 186 - .../management/plugin/report/TestBinaryReport.java | 114 - .../management/plugin/report/TestTextReport.java | 84 - .../rest/ConfiguredObjectToMapConverterTest.java | 410 --- .../plugin/session/LoginLogoutReporterTest.java | 84 - ...pid.server.management.plugin.report.QueueReport | 2 - qpid/java/broker-plugins/management-jmx/pom.xml | 79 - .../apache/qpid/server/jmx/AMQManagedObject.java | 84 - .../qpid/server/jmx/DefaultManagedObject.java | 185 - .../qpid/server/jmx/JMXManagedObjectRegistry.java | 432 --- .../qpid/server/jmx/JMXManagementPlugin.java | 35 - .../qpid/server/jmx/JMXManagementPluginImpl.java | 527 --- .../apache/qpid/server/jmx/MBeanIntrospector.java | 400 --- .../server/jmx/MBeanInvocationHandlerImpl.java | 349 -- .../org/apache/qpid/server/jmx/MBeanProvider.java | 53 - .../org/apache/qpid/server/jmx/ManagedObject.java | 57 - .../qpid/server/jmx/ManagedObjectRegistry.java | 48 - .../server/jmx/ManagementLogonLogoffReporter.java | 143 - .../server/jmx/QpidRMIServerSocketFactory.java | 49 - .../server/jmx/QpidSslRMIServerSocketFactory.java | 120 - .../RegistryProtectingRMIServerSocketFactory.java | 85 - .../apache/qpid/server/jmx/UsernameAccessor.java | 28 - .../server/jmx/UsernameCachingRMIJRMPServer.java | 97 - .../mbeans/AbstractStatisticsGatheringMBean.java | 203 -- .../qpid/server/jmx/mbeans/ConnectionMBean.java | 205 -- .../qpid/server/jmx/mbeans/ExchangeMBean.java | 330 -- .../server/jmx/mbeans/LoggingManagementMBean.java | 332 -- .../apache/qpid/server/jmx/mbeans/QueueMBean.java | 716 ---- .../server/jmx/mbeans/ServerInformationMBean.java | 113 - .../apache/qpid/server/jmx/mbeans/Shutdown.java | 140 - .../qpid/server/jmx/mbeans/ShutdownMBean.java | 58 - .../server/jmx/mbeans/UserManagementMBean.java | 193 - .../qpid/server/jmx/mbeans/VirtualHostMBean.java | 268 -- .../server/jmx/mbeans/VirtualHostManagerMBean.java | 317 -- .../jmx/ManagementLogonLogoffReporterTest.java | 125 - .../qpid/server/jmx/NoopManagedObjectRegistry.java | 46 - .../server/jmx/mbeans/ConnectionMBeanTest.java | 234 -- .../qpid/server/jmx/mbeans/ExchangeMBeanTest.java | 234 -- .../jmx/mbeans/LoggingManagementMBeanTest.java | 245 -- .../qpid/server/jmx/mbeans/MBeanTestUtils.java | 40 - .../qpid/server/jmx/mbeans/QueueMBeanTest.java | 494 --- .../jmx/mbeans/ServerInformationMBeanTest.java | 89 - .../server/jmx/mbeans/UserManagementMBeanTest.java | 157 - .../jmx/mbeans/VirtualHostManagerMBeanTest.java | 268 -- qpid/java/broker-plugins/memory-store/pom.xml | 78 - .../server/store/MemoryConfigurationStore.java | 35 - .../qpid/server/store/MemorySystemConfigImpl.java | 55 - .../virtualhost/memory/MemoryVirtualHost.java | 50 - .../memory/MemoryVirtualHostNode.java | 61 - .../js/qpid/management/virtualhost/memory/add.js | 38 - .../js/qpid/management/virtualhost/memory/edit.js | 28 - .../js/qpid/management/virtualhost/memory/show.js | 33 - .../qpid/management/virtualhostnode/memory/add.js | 40 - .../qpid/management/virtualhostnode/memory/show.js | 38 - .../java/resources/virtualhost/memory/add.html | 22 - .../java/resources/virtualhostnode/memory/add.html | 23 - qpid/java/broker-plugins/websocket/pom.xml | 77 - .../transport/websocket/WebSocketProvider.java | 345 -- .../websocket/WebSocketTransportProvider.java | 52 - .../WebSocketTransportProviderFactory.java | 57 - 514 files changed, 80111 deletions(-) delete mode 100644 qpid/java/broker-plugins/access-control/pom.xml delete mode 100644 qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclAction.java delete mode 100644 qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclRulePredicates.java delete mode 100644 qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.java delete mode 100644 qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ClientAction.java delete mode 100644 qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ConfigurationFile.java delete mode 100644 qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java delete mode 100644 qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Rule.java delete mode 100644 qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java delete mode 100644 qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/AccessControlFirewallException.java delete mode 100644 qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/FirewallRule.java delete mode 100644 qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/FirewallRuleFactory.java delete mode 100644 qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/HostnameFirewallRule.java delete mode 100644 qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/InetNetwork.java delete mode 100644 qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/NetworkFirewallRule.java delete mode 100644 qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProvider.java delete mode 100644 qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderImpl.java delete mode 100644 qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/DefaultAccessControl.java delete mode 100644 qpid/java/broker-plugins/access-control/src/main/resources/acl.xsd delete mode 100644 qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/AclActionTest.java delete mode 100644 qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/AclRulePredicatesTest.java delete mode 100644 qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/ActionTest.java delete mode 100644 qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/ClientActionTest.java delete mode 100644 qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/PlainConfigurationTest.java delete mode 100644 qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/RuleTest.java delete mode 100644 qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/firewall/HostnameFirewallRuleTest.java delete mode 100644 qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/firewall/NetworkFirewallRuleTest.java delete mode 100644 qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderFactoryTest.java delete mode 100644 qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderImplTest.java delete mode 100644 qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/DefaultAccessControlTest.java delete mode 100644 qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/RuleSetTest.java delete mode 100644 qpid/java/broker-plugins/amqp-0-10-protocol/pom.xml delete mode 100644 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ConsumerTarget_0_10.java delete mode 100644 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/CreditCreditManager.java delete mode 100755 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ExplicitAcceptDispositionChangeListener.java delete mode 100755 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/FlowCreditManager_0_10.java delete mode 100755 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ImplicitAcceptDispositionChangeListener.java delete mode 100755 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageAcceptCompletionListener.java delete mode 100644 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_Internal_to_v0_10.java delete mode 100644 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10.java delete mode 100644 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10_to_Internal.java delete mode 100644 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaDataType_0_10.java delete mode 100755 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaData_0_10.java delete mode 100644 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageTransferHeader.java delete mode 100644 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageTransferMessage.java delete mode 100644 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ProtocolEngineCreator_0_10.java delete mode 100755 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ProtocolEngine_0_10.java delete mode 100644 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerAssembler.java delete mode 100644 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerConnection.java delete mode 100644 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerConnectionDelegate.java delete mode 100644 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerDisassembler.java delete mode 100644 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerEncoder.java delete mode 100644 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSession.java delete mode 100644 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSessionDelegate.java delete mode 100644 qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/WindowCreditManager.java delete mode 100644 qpid/java/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/ServerSessionTest.java delete mode 100644 qpid/java/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/WindowCreditManagerTest.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/pom.xml delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQChannel.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQMessage.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQNoMethodHandlerException.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQProtocolEngine.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/BrokerDecoder.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ClientDeliveryMethod.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ConsumerTagInUseException.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ConsumerTarget_0_8.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ExtractResendAndRequeue.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/IncomingMessage.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_Internal_to_v0_8.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_v0_8_to_Internal.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaData.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaDataType_0_8.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageOnlyCreditManager.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/NoAckCreditManager.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/Pre0_10CreditManager.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolEngineCreator_0_8.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolEngineCreator_0_9.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolEngineCreator_0_9_1.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolOutputConverter.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolOutputConverterImpl.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/RecordDeliveryMethod.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/UnacknowledgedMessageMap.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/UnacknowledgedMessageMapImpl.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/UnexpectedMethodException.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQChannelTest.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQProtocolEngineTest.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AckTest.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AcknowledgeTest.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/BrokerTestHelper_0_8.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/ExtractResendAndRequeueTest.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/InternalTestProtocolSession.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/LimitlessCreditManager.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MaxChannelsTest.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MockAMQMessage.java delete mode 100755 qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MockStoredMessage.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/QueueBrowserUsesNoAckTest.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/ReferenceCountingTest.java delete mode 100644 qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/UnacknowledgedMessageMapTest.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/pom.xml delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Connection_1_0.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ConsumerTarget_1_0.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Destination.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ExchangeDestination.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Link_1_0.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_Internal_to_v1_0.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_from_1_0.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_to_1_0.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_v1_0_to_Internal.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaDataType_1_0.java delete mode 100755 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaData_1_0.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageSourceDestination.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Message_1_0.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/NodeReceivingDestination.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ProtocolEngineCreator_1_0_0_SASL.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ProtocolEngine_1_0_0_SASL.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/QueueDestination.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingDestination.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingLinkAttachment.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingLink_1_0.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingDestination.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLinkAttachment.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLink_1_0.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Session_1_0.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/TxnCoordinatorLink_1_0.java delete mode 100644 qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/UnsettledAction.java delete mode 100644 qpid/java/broker-plugins/amqp-msg-conv-0-10-to-1-0/pom.xml delete mode 100644 qpid/java/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_0_10_to_1_0.java delete mode 100644 qpid/java/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_1_0_to_v0_10.java delete mode 100644 qpid/java/broker-plugins/amqp-msg-conv-0-8-to-0-10/pom.xml delete mode 100644 qpid/java/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_10_to_0_8.java delete mode 100644 qpid/java/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_8_to_0_10.java delete mode 100644 qpid/java/broker-plugins/amqp-msg-conv-0-8-to-1-0/pom.xml delete mode 100644 qpid/java/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_0_8_to_1_0.java delete mode 100644 qpid/java/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_1_0_to_v0_8.java delete mode 100644 qpid/java/broker-plugins/derby-store/pom.xml delete mode 100644 qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/AbstractDerbyMessageStore.java delete mode 100644 qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyConfigurationStore.java delete mode 100644 qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyMessageStore.java delete mode 100644 qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbySystemConfig.java delete mode 100644 qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbySystemConfigImpl.java delete mode 100644 qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyUtils.java delete mode 100644 qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhost/derby/DerbyVirtualHost.java delete mode 100644 qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhost/derby/DerbyVirtualHostImpl.java delete mode 100644 qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNode.java delete mode 100644 qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNodeImpl.java delete mode 100644 qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhost/derby/add.js delete mode 100644 qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhost/derby/edit.js delete mode 100644 qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhost/derby/show.js delete mode 100644 qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhostnode/derby/add.js delete mode 100644 qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhostnode/derby/edit.js delete mode 100644 qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhostnode/derby/show.js delete mode 100644 qpid/java/broker-plugins/derby-store/src/main/java/resources/virtualhostnode/derby/add.html delete mode 100644 qpid/java/broker-plugins/derby-store/src/main/java/resources/virtualhostnode/derby/show.html delete mode 100644 qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreConfigurationTest.java delete mode 100644 qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreQuotaEventsTest.java delete mode 100644 qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreTest.java delete mode 100644 qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNodeTest.java delete mode 100644 qpid/java/broker-plugins/jdbc-provider-bone/pom.xml delete mode 100644 qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/org/apache/qpid/server/store/jdbc/bonecp/BoneCPConnectionProvider.java delete mode 100644 qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/org/apache/qpid/server/store/jdbc/bonecp/BoneCPConnectionProviderFactory.java delete mode 100644 qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/js/qpid/management/store/pool/bonecp/add.js delete mode 100644 qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/js/qpid/management/store/pool/bonecp/edit.js delete mode 100644 qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/js/qpid/management/store/pool/bonecp/show.js delete mode 100644 qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/store/pool/bonecp/show.html delete mode 100644 qpid/java/broker-plugins/jdbc-store/pom.xml delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/DefaultConnectionProvider.java delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/DefaultConnectionProviderFactory.java delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericAbstractJDBCMessageStore.java delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCConfigurationStore.java delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCMessageStore.java delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCDetails.java delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSettings.java delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSystemConfig.java delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSystemConfigImpl.java delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhost/jdbc/JDBCVirtualHost.java delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhost/jdbc/JDBCVirtualHostImpl.java delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhostnode/jdbc/JDBCVirtualHostNode.java delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhostnode/jdbc/JDBCVirtualHostNodeImpl.java delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/store/pool/none/add.js delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/store/pool/none/edit.js delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/store/pool/none/show.js delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhost/jdbc/add.js delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhost/jdbc/edit.js delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhost/jdbc/show.js delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhostnode/jdbc/add.js delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhostnode/jdbc/edit.js delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhostnode/jdbc/show.js delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhost/jdbc/add.html delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhost/jdbc/edit.html delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhost/store/pool/none/add.html delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/jdbc/add.html delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/jdbc/edit.html delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/jdbc/show.html delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/store/pool/none/add.html delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/test/java/org/apache/qpid/server/store/jdbc/JDBCDetailsTest.java delete mode 100644 qpid/java/broker-plugins/jdbc-store/src/test/java/org/apache/qpid/server/store/jdbc/JDBCMessageStoreTest.java delete mode 100644 qpid/java/broker-plugins/management-amqp/pom.xml delete mode 100644 qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagedEntityType.java delete mode 100644 qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementNode.java delete mode 100644 qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementNodeConsumer.java delete mode 100644 qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementNodeCreator.java delete mode 100644 qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementResponse.java delete mode 100644 qpid/java/broker-plugins/management-http/pom.xml delete mode 100644 qpid/java/broker-plugins/management-http/src/main/appended-resources/META-INF/LICENSE.vm delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/DojoHelper.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagement.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagementConfiguration.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagementUtil.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/connector/TcpAndSslSelectChannelConnector.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/filter/ForbiddingAuthorisationFilter.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/filter/ForbiddingTraceFilter.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/filter/RedirectingAuthorisationFilter.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/log/LogFileDetails.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/log/LogFileHelper.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/QueueBinaryReport.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/QueueReport.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/QueueTextReport.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportRunner.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportableMessage.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportableMessageHeader.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/DefinedFileServlet.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/FileServlet.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/LogFileServlet.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/ServletConnectionPrincipal.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/AbstractServlet.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/Action.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/ApiDocsServlet.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/ConfiguredObjectToMapConverter.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/HelperServlet.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/KeyComparator.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LogFileListingServlet.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LogRecordsServlet.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LoggedOnUserPreferencesServlet.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LogoutServlet.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MapComparator.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MessageContentServlet.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MessageServlet.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MetaDataServlet.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/PluginClassProviderAction.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/QueueReportServlet.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/RestServlet.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/SaslServlet.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/StructureServlet.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/UserPreferencesServlet.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/AbstractSpecialisedAttributeLister.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListAccessControlProviderAttributes.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListBrokerAttribute.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListGroupProviderAttributes.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListTimeZones.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/session/LoginLogoutReporter.java delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/accesscontrolprovider/aclfile/add.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/accesscontrolprovider/showAclFile.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/addAccessControlProvider.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/addAuthenticationProvider.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/addBinding.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/addExchange.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/addGroupProvider.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/addPort.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/addPreferencesProvider.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/addQueue.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/addStore.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/addVirtualHostNodeAndVirtualHost.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/addUser.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/external/add.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/external/show.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/filebased/add.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/filebased/show.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/setPassword.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/showPrincipalDatabaseAuthenticationManager.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/simpleldap/add.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/simpleldap/show.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/common/ContextVariablesEditor.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/common/ResourceWidget.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/common/TimeZoneSelector.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/css/apidocs.css delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/css/common.css delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/editBroker.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/editQueue.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/editVirtualHost.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/editVirtualHostNode.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/footer.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/grid/showColumnDefDialog.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/grid/showRowNumberLimitDialog.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/group/addGroupMember.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/group/showGroup.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/addGroup.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/groupfile/add.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/groupfile/show.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/showGroupManagingGroupProvider.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/images/auto-refresh.png delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/images/download.png delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/images/gear.png delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/images/help.png delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/images/log-viewer.png delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/images/qpid-logo.png delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/images/refresh.png delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/index.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/README.txt delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/enc-base64-min.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/hmac-sha1.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/hmac-sha256.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/authorization/checkUser.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/authorization/sasl.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/ConsoleHelper.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/ContextVariablesEditor.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/FormWidgetMixin.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/ResourceWidget.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/TimeZoneSelector.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/UpdatableStore.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/footer.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/formatter.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/ColumnDefDialog.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/EnhancedFilter.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/EnhancedFilterTools.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/FilterSummary.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/GridUpdater.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/RowNumberLimitDialog.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/UpdatableGrid.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/metadata.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/properties.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/timezone.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/updater.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/util.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/widgetconfigurer.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/AccessControlProvider.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/AuthenticationProvider.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Broker.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Connection.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Exchange.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/GroupProvider.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/KeyStore.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Plugin.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Port.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Preferences.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/PreferencesProvider.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/Queue.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/TrustStore.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/UserPreferences.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/VirtualHost.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/VirtualHostNode.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/accesscontrolprovider/AclFile.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/accesscontrolprovider/aclfile/add.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addAccessControlProvider.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addAuthenticationProvider.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addBinding.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addExchange.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addGroupProvider.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addPort.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addPreferencesProvider.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addQueue.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addStore.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/addVirtualHostNodeAndVirtualHost.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/PrincipalDatabaseAuthenticationManager.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/anonymous/add.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/anonymous/show.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/base64md5passwordfile/add.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/base64md5passwordfile/show.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/external/add.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/external/show.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/kerberos/add.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/kerberos/show.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/md5/add.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/md5/show.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/plain/add.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/plain/show.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/plainpasswordfile/add.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/plainpasswordfile/show.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/scram-sha-1/add.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/scram-sha-1/show.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/scram-sha-256/add.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/scram-sha-256/show.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/simpleldap/add.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/authenticationprovider/simpleldap/show.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/controller.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/editBroker.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/editQueue.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/editVirtualHost.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/editVirtualHostNode.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/group/Group.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/group/addGroupMember.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/groupprovider/GroupManagingGroupProvider.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/groupprovider/groupfile/add.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/groupprovider/groupfile/show.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/groupprovider/managedgroupprovider/add.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/groupprovider/managedgroupprovider/show.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/logs/LogFileDownloadDialog.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/logs/LogViewer.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/moveCopyMessages.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/plugin/managementhttp.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/plugin/managementjmx.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/preferencesprovider/PreferencesProviderForm.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/preferencesprovider/filesystempreferences/add.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/preferencesprovider/filesystempreferences/show.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/showMessage.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/filekeystore/add.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/filekeystore/show.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/filetruststore/add.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/filetruststore/show.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/nonjavakeystore/add.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/nonjavakeystore/show.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/nonjavatruststore/add.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/store/nonjavatruststore/show.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/treeView.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhost/providedstore/add.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhost/providedstore/edit.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhost/providedstore/show.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhostnode/json/add.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhostnode/json/edit.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/management/virtualhostnode/json/show.js delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/login.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/logs/showLogFileDownloadDialog.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/logs/showLogViewer.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/moveCopyMessages.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/plugin/showManagementHttp.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/plugin/showManagementJmx.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/preferencesprovider/filesystempreferences/add.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/preferencesprovider/filesystempreferences/show.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/preferencesprovider/preferencesProviderForm.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/showAccessControlProvider.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/showAuthProvider.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/showBroker.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/showConnection.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/showExchange.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/showGroupProvider.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/showMessage.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/showPlugin.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/showPort.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/showPreferences.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/showPreferencesProvider.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/showQueue.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/showStore.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/showVirtualHost.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/showVirtualHostNode.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/store/filekeystore/add.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/store/filekeystore/show.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/store/filetruststore/add.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/store/filetruststore/show.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/store/nonjavakeystore/add.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/store/nonjavakeystore/show.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/store/nonjavatruststore/add.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/store/nonjavatruststore/show.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/strings.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/providedstore/add.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/providedstore/edit.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/providedstore/show.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/sizemonitoring/add.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/sizemonitoring/edit.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhost/sizemonitoring/show.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhostnode/filebased/edit.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhostnode/json/add.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/java/resources/virtualhostnode/json/show.html delete mode 100644 qpid/java/broker-plugins/management-http/src/main/resources-maven/dojoconfig.properties delete mode 100644 qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/HttpManagementTest.java delete mode 100644 qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/log/LogFileHelperTest.java delete mode 100644 qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/report/ReportRunnerTest.java delete mode 100644 qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/report/TestBinaryReport.java delete mode 100644 qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/report/TestTextReport.java delete mode 100644 qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/servlet/rest/ConfiguredObjectToMapConverterTest.java delete mode 100644 qpid/java/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/session/LoginLogoutReporterTest.java delete mode 100644 qpid/java/broker-plugins/management-http/src/test/resources/META-INF/services/org.apache.qpid.server.management.plugin.report.QueueReport delete mode 100644 qpid/java/broker-plugins/management-jmx/pom.xml delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/AMQManagedObject.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/DefaultManagedObject.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagedObjectRegistry.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagementPlugin.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagementPluginImpl.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/MBeanIntrospector.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/MBeanInvocationHandlerImpl.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/MBeanProvider.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/ManagedObject.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/ManagedObjectRegistry.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/ManagementLogonLogoffReporter.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/QpidRMIServerSocketFactory.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/QpidSslRMIServerSocketFactory.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/RegistryProtectingRMIServerSocketFactory.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/UsernameAccessor.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/UsernameCachingRMIJRMPServer.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/AbstractStatisticsGatheringMBean.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/ConnectionMBean.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/ExchangeMBean.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/LoggingManagementMBean.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/QueueMBean.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/ServerInformationMBean.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/Shutdown.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/ShutdownMBean.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/UserManagementMBean.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/VirtualHostMBean.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/VirtualHostManagerMBean.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/ManagementLogonLogoffReporterTest.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/NoopManagedObjectRegistry.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/ConnectionMBeanTest.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/ExchangeMBeanTest.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/LoggingManagementMBeanTest.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/MBeanTestUtils.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/QueueMBeanTest.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/ServerInformationMBeanTest.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/UserManagementMBeanTest.java delete mode 100644 qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/mbeans/VirtualHostManagerMBeanTest.java delete mode 100644 qpid/java/broker-plugins/memory-store/pom.xml delete mode 100644 qpid/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/store/MemoryConfigurationStore.java delete mode 100644 qpid/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/store/MemorySystemConfigImpl.java delete mode 100644 qpid/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/virtualhost/memory/MemoryVirtualHost.java delete mode 100644 qpid/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/virtualhostnode/memory/MemoryVirtualHostNode.java delete mode 100644 qpid/java/broker-plugins/memory-store/src/main/java/resources/js/qpid/management/virtualhost/memory/add.js delete mode 100644 qpid/java/broker-plugins/memory-store/src/main/java/resources/js/qpid/management/virtualhost/memory/edit.js delete mode 100644 qpid/java/broker-plugins/memory-store/src/main/java/resources/js/qpid/management/virtualhost/memory/show.js delete mode 100644 qpid/java/broker-plugins/memory-store/src/main/java/resources/js/qpid/management/virtualhostnode/memory/add.js delete mode 100644 qpid/java/broker-plugins/memory-store/src/main/java/resources/js/qpid/management/virtualhostnode/memory/show.js delete mode 100644 qpid/java/broker-plugins/memory-store/src/main/java/resources/virtualhost/memory/add.html delete mode 100644 qpid/java/broker-plugins/memory-store/src/main/java/resources/virtualhostnode/memory/add.html delete mode 100644 qpid/java/broker-plugins/websocket/pom.xml delete mode 100644 qpid/java/broker-plugins/websocket/src/main/java/org/apache/qpid/server/transport/websocket/WebSocketProvider.java delete mode 100644 qpid/java/broker-plugins/websocket/src/main/java/org/apache/qpid/server/transport/websocket/WebSocketTransportProvider.java delete mode 100644 qpid/java/broker-plugins/websocket/src/main/java/org/apache/qpid/server/transport/websocket/WebSocketTransportProviderFactory.java (limited to 'qpid/java/broker-plugins') diff --git a/qpid/java/broker-plugins/access-control/pom.xml b/qpid/java/broker-plugins/access-control/pom.xml deleted file mode 100644 index ab6cf90a21..0000000000 --- a/qpid/java/broker-plugins/access-control/pom.xml +++ /dev/null @@ -1,91 +0,0 @@ - - - - 4.0.0 - - - org.apache.qpid - qpid-java-build - 0.32-SNAPSHOT - ../../pom.xml - - - qpid-broker-plugins-access-control - Qpid Access Control Broker Plug-in - Access Control broker plug-in - - - ${project.build.directory}/generated-sources/generated-logmessages - - - - - org.apache.qpid - qpid-broker-core - ${project.version} - provided - - - - org.apache.qpid - qpid-broker-codegen - ${project.version} - true - - - - log4j - log4j - ${log4j-version} - - - - - org.apache.qpid - qpid-test-utils - ${project.version} - test - - - - org.apache.qpid - qpid-broker-core - ${project.version} - test-jar - test - - - - - - - src/main/java - - **/*.java - - - - src/main/resources - - META-INF/ - - - - - - diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclAction.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclAction.java deleted file mode 100644 index e4bf21a082..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclAction.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.config; - -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; -import org.apache.qpid.server.security.access.firewall.FirewallRule; - -public class AclAction -{ - private Action _action; - private FirewallRule _firewallRule; - - public AclAction(Operation operation, ObjectType object, AclRulePredicates predicates) - { - _action = new Action(operation, object, predicates.getObjectProperties()); - _firewallRule = predicates.getFirewallRule(); - } - - public AclAction(Operation operation) - { - _action = new Action(operation); - } - - public AclAction(Operation operation, ObjectType object, ObjectProperties properties) - { - _action = new Action(operation, object, properties); - } - - public FirewallRule getFirewallRule() - { - return _firewallRule; - } - - public Action getAction() - { - return _action; - } - - public boolean isAllowed() - { - return _action.isAllowed(); - } - - @Override - public int hashCode() - { - return new HashCodeBuilder() - .append(_action) - .append(_firewallRule).toHashCode(); - } - - @Override - public boolean equals(Object obj) - { - if (obj == null) - { - return false; - } - if (obj == this) - { - return true; - } - if (obj.getClass() != getClass()) - { - return false; - } - AclAction rhs = (AclAction) obj; - return new EqualsBuilder() - .append(_action, rhs._action) - .append(_firewallRule, rhs._firewallRule).isEquals(); - } - - @Override - public String toString() - { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append(_action) - .append(_firewallRule).toString(); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclRulePredicates.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclRulePredicates.java deleted file mode 100644 index ebe6df126f..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AclRulePredicates.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.security.access.config; - -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectProperties.Property; -import org.apache.qpid.server.security.access.firewall.FirewallRule; -import org.apache.qpid.server.security.access.firewall.FirewallRuleFactory; - -/** - * Represents the predicates on an ACL rule by combining predicates relating to the object being operated on - * (e.g. name=foo) with firewall rules. - */ -public class AclRulePredicates -{ - private static final Logger _logger = LoggerFactory.getLogger(AclRulePredicates.class); - - private static final String SEPARATOR = ","; - - private ObjectProperties _properties = new ObjectProperties(); - - private FirewallRule _firewallRule; - - private FirewallRuleFactory _firewallRuleFactory = new FirewallRuleFactory(); - - public void parse(String key, String value) - { - ObjectProperties.Property property = ObjectProperties.Property.parse(key); - - if(property == Property.FROM_HOSTNAME) - { - checkFirewallRuleNotAlreadyDefined(key, value); - _firewallRule = _firewallRuleFactory.createForHostname(value.split(SEPARATOR)); - } - else if(property == Property.FROM_NETWORK) - { - checkFirewallRuleNotAlreadyDefined(key, value); - _firewallRule = _firewallRuleFactory.createForNetwork(value.split(SEPARATOR)); - } - else - { - _properties.put(property, value); - } - - if (_logger.isDebugEnabled()) - { - _logger.debug("Parsed " + property + " with value " + value); - } - } - - private void checkFirewallRuleNotAlreadyDefined(String key, String value) - { - if(_firewallRule != null) - { - throw new IllegalStateException( - "Cannot parse " + key + "=" + value - + " because firewall rule " + _firewallRule + " has already been defined"); - } - } - - @Override - public String toString() - { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append(_properties) - .append(_firewallRule).toString(); - } - - public FirewallRule getFirewallRule() - { - return _firewallRule; - } - - public ObjectProperties getObjectProperties() - { - return _properties; - } - - void setFirewallRuleFactory(FirewallRuleFactory firewallRuleFactory) - { - _firewallRuleFactory = firewallRuleFactory; - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.java deleted file mode 100644 index e09935cf5c..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.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.server.security.access.config; - -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 java.util.Map}. - * The operation and object should be an allowable combination, based on the {@link ObjectType#isAllowed(Operation)} - * method of the object, which is exposed as the {@link #isAllowed()} method here. The internal #propertiesMatch(Map) - * and #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. - *

- * 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 final Operation _operation; - private final ObjectType _object; - private final 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) - { - _operation = operation; - _object = object; - _properties = properties; - } - - public Operation getOperation() - { - return _operation; - } - - public ObjectType getObjectType() - { - return _object; - } - - public ObjectProperties getProperties() - { - return _properties; - } - - public boolean isAllowed() - { - return _object.isAllowed(_operation); - } - - public boolean matches(Action a) - { - if (!operationsMatch(a)) - { - return false; - } - - if (!objectTypesMatch(a)) - { - return false; - } - - if (!propertiesMatch(a)) - { - return false; - } - - return true; - } - - private boolean operationsMatch(Action a) - { - return Operation.ALL == a.getOperation() || getOperation() == a.getOperation(); - } - - private boolean objectTypesMatch(Action a) - { - return ObjectType.ALL == a.getObjectType() || getObjectType() == a.getObjectType(); - } - - private boolean propertiesMatch(Action a) - { - boolean propertiesMatch = false; - if (_properties != null) - { - propertiesMatch = _properties.matches(a.getProperties()); - } - else if (a.getProperties() == null) - { - propertiesMatch = true; - } - return propertiesMatch; - } - - @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()) - .append(_properties, a.getProperties()) - .isEquals(); - } - - @Override - public int hashCode() - { - return new HashCodeBuilder() - .append(_operation) - .append(_object) - .append(_properties) - .toHashCode(); - } - - @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/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ClientAction.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ClientAction.java deleted file mode 100644 index fed20a56c8..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ClientAction.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.access.config; - -import java.net.InetAddress; - -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; -import org.apache.qpid.server.security.access.firewall.FirewallRule; - -/** - * I represent an {@link Action} taken by a client from a known address. The address is used to - * determine if I match an {@link AclAction}, which may contain firewall rules. - */ -public class ClientAction -{ - private Action _clientAction; - - public ClientAction(Action clientAction) - { - _clientAction = clientAction; - } - - public ClientAction(Operation operation, ObjectType objectType, ObjectProperties properties) - { - _clientAction = new Action(operation, objectType, properties); - } - - public boolean matches(AclAction ruleAction, InetAddress addressOfClient) - { - return _clientAction.matches(ruleAction.getAction()) - && addressOfClientMatches(ruleAction, addressOfClient); - } - - private boolean addressOfClientMatches(AclAction ruleAction, InetAddress addressOfClient) - { - FirewallRule firewallRule = ruleAction.getFirewallRule(); - if(firewallRule == null || addressOfClient == null) - { - return true; - } - else - { - return firewallRule.matches(addressOfClient); - } - } - - public Operation getOperation() - { - return _clientAction.getOperation(); - } - - public ObjectType getObjectType() - { - return _clientAction.getObjectType(); - } - - public ObjectProperties getProperties() - { - return _clientAction.getProperties(); - } - - @Override - public String toString() - { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append(_clientAction).toString(); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ConfigurationFile.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ConfigurationFile.java deleted file mode 100644 index 3405b6c155..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ConfigurationFile.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.access.config; - -import java.io.Reader; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; - -public interface ConfigurationFile -{ - /** - * Load this configuration file's contents into a {@link RuleSet}. - * @throws IllegalConfigurationException if the configuration file has errors. - * @throws IllegalArgumentException if individual tokens cannot be parsed. - * @param configReader - */ - RuleSet load(final Reader configReader) throws IllegalConfigurationException; - - RuleSet getConfiguration(); - -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java deleted file mode 100644 index 92b870f740..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.FileNotFoundException; -import java.io.IOException; -import java.io.Reader; -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.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.logging.EventLoggerProvider; -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 implements ConfigurationFile -{ - private static final Logger _logger = LoggerFactory.getLogger(PlainConfiguration.class); - - public static final Character COMMENT = '#'; - public static final Character CONTINUATION = '\\'; - - public static final String ACL = "acl"; - public static final String CONFIG = "config"; - - static final String UNRECOGNISED_INITIAL_MSG = "Unrecognised initial token '%s' at line %d"; - static final String NOT_ENOUGH_TOKENS_MSG = "Not enough tokens at line %d"; - static final String NUMBER_NOT_ALLOWED_MSG = "Number not allowed before '%s' at line %d"; - static final String CANNOT_LOAD_MSG = "Cannot load config file %s"; - static final String CANNOT_CLOSE_MSG = "Cannot close config file %s"; - static final String PREMATURE_CONTINUATION_MSG = "Premature continuation character at line %d"; - static final String PREMATURE_EOF_MSG = "Premature end of file reached at line %d"; - static final String PARSE_TOKEN_FAILED_MSG = "Failed to parse token at line %d"; - static final String CONFIG_NOT_FOUND_MSG = "Cannot find config file %s"; - static final String NOT_ENOUGH_ACL_MSG = "Not enough data for an acl at line %d"; - static final String NOT_ENOUGH_CONFIG_MSG = "Not enough data for config at line %d"; - static final String BAD_ACL_RULE_NUMBER_MSG = "Invalid rule number at line %d"; - static final String PROPERTY_KEY_ONLY_MSG = "Incomplete property (key only) at line %d"; - static final String PROPERTY_NO_EQUALS_MSG = "Incomplete property (no equals) at line %d"; - static final String PROPERTY_NO_VALUE_MSG = "Incomplete property (no value) at line %d"; - private final EventLoggerProvider _eventLogger; - private final String _name; - - private StreamTokenizer _st; - private RuleSet _config; - - public PlainConfiguration(String name, final EventLoggerProvider eventLogger) - { - _eventLogger = eventLogger; - _name = name; - } - - @Override - public RuleSet load(final Reader configReader) - { - _config = new RuleSet(_eventLogger); - - try(Reader fileReader = configReader) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("About to load ACL file"); - } - - _st = new StreamTokenizer(new BufferedReader(fileReader)); - _st.resetSyntax(); // setup the tokenizer - - _st.commentChar(COMMENT); // single line comments - _st.eolIsSignificant(true); // return EOL as a token - _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 stack = new Stack(); - 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 IllegalConfigurationException(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)) - { - throw new IllegalConfigurationException(String.format("GROUP keyword not supported at line %d. Groups should defined via a Group Provider, not in the ACL file.", getLine())); - } - else if (StringUtils.equalsIgnoreCase(CONFIG, first)) - { - parseConfig(stack); - } - else - { - throw new IllegalConfigurationException(String.format(UNRECOGNISED_INITIAL_MSG, first, getLine())); - } - } - else - { - throw new IllegalConfigurationException(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 because we ate the EOL) - throw new IllegalConfigurationException(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 IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, getLine())); - } - } - catch (IllegalArgumentException iae) - { - throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, getLine()), iae); - } - catch (FileNotFoundException fnfe) - { - throw new IllegalConfigurationException(String.format(CONFIG_NOT_FOUND_MSG, _name), fnfe); - } - catch (IOException ioe) - { - throw new IllegalConfigurationException(String.format(CANNOT_LOAD_MSG, _name), ioe); - } - - return _config; - } - - private void parseAcl(Integer number, List args) - { - if (args.size() < 3) - { - throw new IllegalConfigurationException(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 IllegalConfigurationException(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)); - AclRulePredicates predicates = toRulePredicates(args.subList(4, args.size())); - - getConfiguration().grant(number, identity, permission, operation, object, predicates); - } - } - - private void parseConfig(List args) - { - if (args.size() < 3) - { - throw new IllegalConfigurationException(String.format(NOT_ENOUGH_CONFIG_MSG, getLine())); - } - - Map properties = toPluginProperties(args); - - getConfiguration().configure(properties); - } - - private AclRulePredicates toRulePredicates(List args) - { - AclRulePredicates predicates = new AclRulePredicates(); - Iterator i = args.iterator(); - while (i.hasNext()) - { - String key = i.next(); - if (!i.hasNext()) - { - throw new IllegalConfigurationException(String.format(PROPERTY_KEY_ONLY_MSG, getLine())); - } - if (!"=".equals(i.next())) - { - throw new IllegalConfigurationException(String.format(PROPERTY_NO_EQUALS_MSG, getLine())); - } - if (!i.hasNext()) - { - throw new IllegalConfigurationException(String.format(PROPERTY_NO_VALUE_MSG, getLine())); - } - String value = i.next(); - - predicates.parse(key, value); - } - return predicates; - } - - /** Converts a {@link List} of "name", "=", "value" tokens into a {@link Map}. */ - protected Map toPluginProperties(List args) - { - Map properties = new HashMap(); - Iterator i = args.iterator(); - while (i.hasNext()) - { - String key = i.next().toLowerCase(); - if (!i.hasNext()) - { - throw new IllegalConfigurationException(String.format(PROPERTY_KEY_ONLY_MSG, getLine())); - } - if (!"=".equals(i.next())) - { - throw new IllegalConfigurationException(String.format(PROPERTY_NO_EQUALS_MSG, getLine())); - } - if (!i.hasNext()) - { - throw new IllegalConfigurationException(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; - } - - public RuleSet getConfiguration() - { - return _config; - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Rule.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Rule.java deleted file mode 100644 index 9e9b33194e..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Rule.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.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 -{ - /** String indicating all identified. */ - public static final String ALL = "all"; - - private Integer _number; - private Boolean _enabled = Boolean.TRUE; - private String _identity; - private AclAction _action; - private Permission _permission; - - public Rule(Integer number, String identity, AclAction action, Permission permission) - { - setNumber(number); - setIdentity(identity); - setAction(action); - setPermission(permission); - } - - public Rule(String identity, AclAction 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.getAction(); - } - - public AclAction getAclAction() - { - return _action; - } - - public void setAction(AclAction action) - { - _action = action; - } - - public Permission getPermission() - { - return _permission; - } - - public void setPermission(Permission permission) - { - _permission = permission; - } - - @Override - public int compareTo(Rule r) - { - return new CompareToBuilder() - .append(getAction(), r.getAction()) - .append(getIdentity(), r.getIdentity()) - .append(getPermission(), r.getPermission()) - .toComparison(); - } - - @Override - public boolean equals(Object o) - { - if (!(o instanceof Rule)) - { - return false; - } - Rule r = (Rule) o; - - return new EqualsBuilder() - .append(getIdentity(), r.getIdentity()) - .append(getAclAction(), r.getAclAction()) - .append(getPermission(), r.getPermission()) - .isEquals(); - } - - @Override - public int hashCode() - { - return new HashCodeBuilder() - .append(getIdentity()) - .append(getAclAction()) - .append(getPermission()) - .toHashCode(); - } - - @Override - public String toString() - { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append("#", getNumber()) - .append("identity", getIdentity()) - .append("action", getAclAction()) - .append("permission", getPermission()) - .append("enabled", isEnabled()) - .toString(); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java deleted file mode 100644 index 7661951d8b..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.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.security.access.config; - -import java.net.InetAddress; -import java.security.Principal; -import java.util.Arrays; -import java.util.Collections; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.WeakHashMap; - -import javax.security.auth.Subject; - -import org.apache.commons.lang.BooleanUtils; -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.EventLoggerProvider; -import org.apache.qpid.server.logging.messages.AccessControlMessages; -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; - -/** - * Models the rule configuration for the access control plugin. - */ -public class RuleSet implements EventLoggerProvider -{ - private static final Logger _logger = LoggerFactory.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 List CONFIG_PROPERTIES = Arrays.asList(DEFAULT_ALLOW, DEFAULT_DENY); - - private static final Integer _increment = 10; - - private final SortedMap _rules = new TreeMap(); - private final Map>>> _cache = - new WeakHashMap>>>(); - private final Map _config = new HashMap(); - private final EventLoggerProvider _eventLogger; - - public RuleSet(EventLoggerProvider eventLogger) - { - _eventLogger = eventLogger; - // set some default configuration properties - configure(DEFAULT_DENY, Boolean.TRUE); - } - - /** - * Clear the contents, including acl rules and configuration. - */ - public void clear() - { - _rules.clear(); - _cache.clear(); - _config.clear(); - } - - public int getRuleCount() - { - return _rules.size(); - } - - /** - * Filtered rules list based on a subject 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 getRules(final Subject subject, final Operation operation, final ObjectType objectType) - { - final Map> objects = getObjectToRuleCache(subject, operation); - - // Lookup object type rules for the operation - if (!objects.containsKey(objectType)) - { - final Set principals = subject.getPrincipals(); - boolean controlled = false; - List filtered = new LinkedList(); - for (Rule rule : _rules.values()) - { - final Action ruleAction = rule.getAction(); - if (rule.isEnabled() - && (ruleAction.getOperation() == Operation.ALL || ruleAction.getOperation() == operation) - && (ruleAction.getObjectType() == ObjectType.ALL || ruleAction.getObjectType() == objectType)) - { - controlled = true; - - if (isRelevant(principals,rule)) - { - 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); - if(_logger.isDebugEnabled()) - { - _logger.debug("Cached " + objectType + " RulesList: " + filtered); - } - } - - // Return the cached rules - List rules = objects.get(objectType); - if(_logger.isDebugEnabled()) - { - _logger.debug("Returning RuleList: " + rules); - } - - return rules; - } - - public boolean isValidNumber(Integer number) - { - return !_rules.containsKey(number); - } - - public void grant(Integer number, String identity, Permission permission, Operation operation) - { - AclAction action = new AclAction(operation); - addRule(number, identity, permission, action); - } - - public void grant(Integer number, String identity, Permission permission, Operation operation, ObjectType object, ObjectProperties properties) - { - AclAction action = new AclAction(operation, object, properties); - addRule(number, identity, permission, action); - } - - public void grant(Integer number, String identity, Permission permission, Operation operation, ObjectType object, AclRulePredicates predicates) - { - AclAction aclAction = new AclAction(operation, object, predicates); - addRule(number, identity, permission, aclAction); - } - - public boolean ruleExists(String identity, AclAction action) - { - for (Rule rule : _rules.values()) - { - if (rule.getIdentity().equals(identity) && rule.getAclAction().equals(action)) - { - return true; - } - } - return false; - } - - public void addRule(Integer number, String identity, Permission permission, AclAction action) - { - - if (!action.isAllowed()) - { - throw new IllegalArgumentException("Action is not allowed: " + action); - } - if (ruleExists(identity, action)) - { - return; - } - - // 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.clear(); - _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(); - } - - /** 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 name - 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; - } - - /** - * Checks for the case when the client's address is not known. - * - * @see #check(Subject, Operation, ObjectType, ObjectProperties, InetAddress) - */ - public Result check(Subject subject, Operation operation, ObjectType objectType, ObjectProperties properties) - { - return check(subject, operation, objectType, properties, null); - } - - /** - * Check the authorisation granted to a particular identity for an operation on an object type with - * specific properties. - * - * Looks up the entire ruleset, which 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(Subject subject, Operation operation, ObjectType objectType, ObjectProperties properties, InetAddress addressOfClient) - { - ClientAction action = new ClientAction(operation, objectType, properties); - - if(_logger.isDebugEnabled()) - { - _logger.debug("Checking action: " + action); - } - - // get the list of rules relevant for this request - List rules = getRules(subject, operation, objectType); - if (rules == null) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("No rules found, returning default result"); - } - return getDefault(); - } - - // Iterate through a filtered set of rules dealing with this identity and operation - for (Rule rule : rules) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("Checking against rule: " + rule); - } - - if (action.matches(rule.getAclAction(), addressOfClient)) - { - Permission permission = rule.getPermission(); - - switch (permission) - { - case ALLOW_LOG: - getEventLogger().message(AccessControlMessages.ALLOWED( - action.getOperation().toString(), - action.getObjectType().toString(), - action.getProperties().toString())); - case ALLOW: - return Result.ALLOWED; - case DENY_LOG: - getEventLogger().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 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); - } - - /** - * Returns all rules in the {@link RuleSet}. Primarily intended to support unit-testing. - * @return map of rules - */ - public Map getAllRules() - { - return Collections.unmodifiableMap(_rules); - } - - private boolean isRelevant(final Set principals, final Rule rule) - { - if (rule.getIdentity().equalsIgnoreCase(Rule.ALL)) - { - return true; - } - else - { - for (Iterator iterator = principals.iterator(); iterator.hasNext();) - { - final Principal principal = iterator.next(); - - if (rule.getIdentity().equalsIgnoreCase(principal.getName())) - { - return true; - } - } - } - - return false; - } - - private Map> getObjectToRuleCache(final Subject subject, final Operation operation) - { - // Lookup identity in cache and create empty operation map if required - Map>> operations = _cache.get(subject); - if (operations == null) - { - operations = new EnumMap>>(Operation.class); - _cache.put(subject, operations); - } - - // Lookup operation and create empty object type map if required - Map> objects = operations.get(operation); - if (objects == null) - { - objects = new EnumMap>(ObjectType.class); - operations.put(operation, objects); - } - return objects; - } - - public EventLogger getEventLogger() - { - return _eventLogger.getEventLogger(); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/AccessControlFirewallException.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/AccessControlFirewallException.java deleted file mode 100644 index d08a052efd..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/AccessControlFirewallException.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.firewall; - -public class AccessControlFirewallException extends RuntimeException -{ - /** serialVersionUID */ - private static final long serialVersionUID = 4526157149690917805L; - - public AccessControlFirewallException() - { - super(); - } - - public AccessControlFirewallException(String message) - { - super(message); - } - - public AccessControlFirewallException(String message, Throwable cause) - { - super(message, cause); - } - - public AccessControlFirewallException(Throwable cause) - { - super(cause); - } -} \ No newline at end of file diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/FirewallRule.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/FirewallRule.java deleted file mode 100644 index 482a795693..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/FirewallRule.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.security.access.firewall; - -import java.net.InetAddress; - -public interface FirewallRule -{ - boolean matches(InetAddress addressOfClient); -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/FirewallRuleFactory.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/FirewallRuleFactory.java deleted file mode 100644 index 64be26c209..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/FirewallRuleFactory.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.security.access.firewall; - -public class FirewallRuleFactory -{ - public FirewallRule createForHostname(String[] hostnames) - { - return new HostnameFirewallRule(hostnames); - } - - public FirewallRule createForNetwork(String[] networks) - { - return new NetworkFirewallRule(networks); - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/HostnameFirewallRule.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/HostnameFirewallRule.java deleted file mode 100644 index 9d62c44658..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/HostnameFirewallRule.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.security.access.firewall; - -import java.net.InetAddress; -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.regex.Pattern; - -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.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class HostnameFirewallRule implements FirewallRule -{ - private static final Logger _logger = LoggerFactory.getLogger(HostnameFirewallRule.class); - - private static final long DNS_TIMEOUT = 30000; - private static final ExecutorService DNS_LOOKUP = Executors.newCachedThreadPool(); - - private Pattern[] _hostnamePatterns; - private String[] _hostnames; - - public HostnameFirewallRule(String... hostnames) - { - _hostnames = hostnames; - - int i = 0; - _hostnamePatterns = new Pattern[hostnames.length]; - for (String hostname : hostnames) - { - _hostnamePatterns[i++] = Pattern.compile(hostname); - } - - if(_logger.isDebugEnabled()) - { - _logger.debug("Created " + this); - } - } - - @Override - public boolean matches(InetAddress remote) - { - String hostname = getHostname(remote); - if (hostname == null) - { - throw new AccessControlFirewallException("DNS lookup failed for address " + remote); - } - for (Pattern pattern : _hostnamePatterns) - { - boolean hostnameMatches = pattern.matcher(hostname).matches(); - - if (hostnameMatches) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("Hostname " + hostname + " matches rule " + pattern.toString()); - } - return true; - } - } - - if(_logger.isDebugEnabled()) - { - _logger.debug("Hostname " + hostname + " matches no configured hostname patterns"); - } - - return false; - } - - - /** - * @param remote - * the InetAddress to look up - * @return the hostname, null if not found, takes longer than - * {@value #DNS_LOOKUP} to find or otherwise fails - */ - private String getHostname(final InetAddress remote) throws AccessControlFirewallException - { - FutureTask lookup = new FutureTask(new Callable() - { - public String call() - { - return remote.getCanonicalHostName(); - } - }); - DNS_LOOKUP.execute(lookup); - - try - { - return lookup.get(DNS_TIMEOUT, TimeUnit.MILLISECONDS); - } - catch (Exception e) - { - _logger.warn("Unable to look up hostname from address " + remote, e); - return null; - } - finally - { - lookup.cancel(true); - } - } - - @Override - public int hashCode() - { - return new HashCodeBuilder().append(_hostnames).toHashCode(); - } - - @Override - public boolean equals(Object obj) - { - if (obj == null) - { - return false; - } - if (obj == this) - { - return true; - } - if (obj.getClass() != getClass()) - { - return false; - } - HostnameFirewallRule rhs = (HostnameFirewallRule) obj; - return new EqualsBuilder().append(_hostnames, rhs._hostnames).isEquals(); - } - - @Override - public String toString() - { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append(_hostnames).toString(); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/InetNetwork.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/InetNetwork.java deleted file mode 100644 index 7294d9c5e8..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/InetNetwork.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.security.access.firewall; - -import java.net.InetAddress; - -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) - { - this.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)); - } - - @Override - public String toString() - { - return network.getHostAddress() + "/" + netmask.getHostAddress(); - } - - @Override - public int hashCode() - { - return maskIP(network, netmask).hashCode(); - } - - @Override - 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 InetAddress.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); - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/NetworkFirewallRule.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/NetworkFirewallRule.java deleted file mode 100644 index 4d635a600e..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/firewall/NetworkFirewallRule.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.security.access.firewall; - -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.List; - -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.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class NetworkFirewallRule implements FirewallRule -{ - private static final Logger _logger = LoggerFactory.getLogger(NetworkFirewallRule.class); - - private List _networks; - - public NetworkFirewallRule(String... networks) - { - _networks = new ArrayList(); - for (int i = 0; i < networks.length; i++) - { - String network = networks[i]; - try - { - InetNetwork inetNetwork = InetNetwork.getFromString(network); - if (!_networks.contains(inetNetwork)) - { - _networks.add(inetNetwork); - } - } - catch (java.net.UnknownHostException uhe) - { - _logger.error("Cannot resolve address: " + network, uhe); - } - } - - if(_logger.isDebugEnabled()) - { - _logger.debug("Created " + this); - } - } - - @Override - public boolean matches(InetAddress ip) - { - for (InetNetwork network : _networks) - { - if (network.contains(ip)) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("Client address " + ip + " matches configured network " + network); - } - return true; - } - } - - if(_logger.isDebugEnabled()) - { - _logger.debug("Client address " + ip + " does not match any configured networks"); - } - - return false; - } - - @Override - public int hashCode() - { - return new HashCodeBuilder().append(_networks).toHashCode(); - } - - @Override - public boolean equals(Object obj) - { - if (obj == null) - { - return false; - } - if (obj == this) - { - return true; - } - if (obj.getClass() != getClass()) - { - return false; - } - NetworkFirewallRule rhs = (NetworkFirewallRule) obj; - return new EqualsBuilder().append(_networks, rhs._networks).isEquals(); - } - - @Override - public String toString() - { - return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) - .append(_networks).toString(); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProvider.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProvider.java deleted file mode 100644 index 3e0f5b63f0..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProvider.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.server.security.access.plugins; - -import org.apache.qpid.server.model.AccessControlProvider; -import org.apache.qpid.server.model.ManagedAttribute; -import org.apache.qpid.server.model.ManagedObject; - -@ManagedObject( category = false, type="AclFile" ) -public interface ACLFileAccessControlProvider> extends AccessControlProvider -{ - @ManagedAttribute( mandatory = true, description = "File location", oversize = true, oversizedAltText = OVER_SIZED_ATTRIBUTE_ALTERNATIVE_TEXT) - String getPath(); -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderImpl.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderImpl.java deleted file mode 100644 index 7023a9a03b..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderImpl.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.security.access.plugins; - -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.SettableFuture; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.AbstractConfiguredObject; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.ManagedAttributeField; -import org.apache.qpid.server.model.ManagedObjectFactoryConstructor; -import org.apache.qpid.server.model.State; -import org.apache.qpid.server.model.StateTransition; -import org.apache.qpid.server.security.AccessControl; -import org.apache.qpid.server.util.urlstreamhandler.data.Handler; - -public class ACLFileAccessControlProviderImpl - extends AbstractConfiguredObject - implements ACLFileAccessControlProvider -{ - private static final Logger LOGGER = LoggerFactory.getLogger(ACLFileAccessControlProviderImpl.class); - - static - { - Handler.register(); - } - - protected DefaultAccessControl _accessControl; - protected final Broker _broker; - - @ManagedAttributeField( afterSet = "reloadAclFile") - private String _path; - - @ManagedObjectFactoryConstructor - public ACLFileAccessControlProviderImpl(Map attributes, Broker broker) - { - super(parentsMap(broker), attributes); - - - _broker = broker; - - } - - @Override - public void onValidate() - { - super.onValidate(); - if(!isDurable()) - { - throw new IllegalArgumentException(getClass().getSimpleName() + " must be durable"); - } - } - - @Override - protected void validateChange(final ConfiguredObject proxyForValidation, final Set changedAttributes) - { - super.validateChange(proxyForValidation, changedAttributes); - if(changedAttributes.contains(DURABLE) && !proxyForValidation.isDurable()) - { - throw new IllegalArgumentException(getClass().getSimpleName() + " must be durable"); - } - } - - @Override - protected void validateOnCreate() - { - DefaultAccessControl accessControl = null; - try - { - accessControl = new DefaultAccessControl(getPath(), _broker); - accessControl.validate(); - accessControl.open(); - } - catch(RuntimeException e) - { - throw new IllegalConfigurationException(e.getMessage(), e); - } - finally - { - if (accessControl != null) - { - accessControl.close(); - } - } - } - - @Override - protected void onOpen() - { - super.onOpen(); - _accessControl = new DefaultAccessControl(getPath(), _broker); - } - - @SuppressWarnings("unused") - private void reloadAclFile() - { - try - { - DefaultAccessControl accessControl = new DefaultAccessControl(getPath(), _broker); - accessControl.open(); - DefaultAccessControl oldAccessControl = _accessControl; - _accessControl = accessControl; - if(oldAccessControl != null) - { - oldAccessControl.close(); - } - } - catch(RuntimeException e) - { - throw new IllegalConfigurationException(e.getMessage(), e); - } - } - - @Override - public String getPath() - { - return _path; - } - - @Override - public Collection getChildren(Class clazz) - { - return Collections.emptySet(); - } - - - @StateTransition(currentState = {State.UNINITIALIZED, State.QUIESCED, State.ERRORED}, desiredState = State.ACTIVE) - private ListenableFuture activate() - { - - if(_broker.isManagementMode()) - { - - setState(_accessControl.validate() ? State.QUIESCED : State.ERRORED); - } - else - { - try - { - _accessControl.open(); - setState(State.ACTIVE); - } - catch (RuntimeException e) - { - setState(State.ERRORED); - if (_broker.isManagementMode()) - { - LOGGER.warn("Failed to activate ACL provider: " + getName(), e); - } - else - { - throw e; - } - } - } - return Futures.immediateFuture(null); - } - - @Override - protected void onClose() - { - super.onClose(); - if (_accessControl != null) - { - _accessControl.close(); - } - } - - @StateTransition(currentState = State.UNINITIALIZED, desiredState = State.QUIESCED) - private ListenableFuture startQuiesced() - { - setState(State.QUIESCED); - return Futures.immediateFuture(null); - } - - @StateTransition(currentState = {State.ACTIVE, State.QUIESCED, State.ERRORED}, desiredState = State.DELETED) - private ListenableFuture doDelete() - { - final SettableFuture returnVal = SettableFuture.create(); - closeAsync().addListener( - new Runnable() - { - @Override - public void run() - { - try - { - - setState(State.DELETED); - deleted(); - } - finally - { - returnVal.set(null); - } - } - }, getTaskExecutor().getExecutor() - ); - return returnVal; - } - - public AccessControl getAccessControl() - { - return _accessControl; - } -} diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/DefaultAccessControl.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/DefaultAccessControl.java deleted file mode 100644 index 8533166023..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/DefaultAccessControl.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.security.access.plugins; - -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.MalformedURLException; -import java.net.SocketAddress; -import java.net.URL; -import java.security.AccessController; -import java.util.Set; - -import javax.security.auth.Subject; - -import org.apache.commons.lang.ObjectUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.connection.ConnectionPrincipal; -import org.apache.qpid.server.logging.EventLoggerProvider; -import org.apache.qpid.server.security.AccessControl; -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.config.ConfigurationFile; -import org.apache.qpid.server.security.access.config.PlainConfiguration; -import org.apache.qpid.server.security.access.config.RuleSet; - -public class DefaultAccessControl implements AccessControl -{ - private static final Logger _logger = LoggerFactory.getLogger(DefaultAccessControl.class); - private final String _fileName; - - private RuleSet _ruleSet; - private final EventLoggerProvider _eventLogger; - - public DefaultAccessControl(String name, final EventLoggerProvider eventLogger) - { - _fileName = name; - _eventLogger = eventLogger; - if (_logger.isDebugEnabled()) - { - _logger.debug("Creating AccessControl instance"); - } - } - - DefaultAccessControl(RuleSet rs) - { - _fileName = null; - _ruleSet = rs; - _eventLogger = rs; - } - - public void open() - { - if(_fileName != null) - { - ConfigurationFile configFile = new PlainConfiguration(_fileName, _eventLogger); - _ruleSet = configFile.load(getReaderFromURLString(_fileName)); - } - } - - @Override - public boolean validate() - { - try - { - getReaderFromURLString(_fileName); - return true; - } - catch(IllegalConfigurationException e) - { - return false; - } - } - - - private static Reader getReaderFromURLString(String urlString) - { - try - { - URL url; - - try - { - url = new URL(urlString); - } - catch (MalformedURLException e) - { - File file = new File(urlString); - try - { - url = file.toURI().toURL(); - } - catch (MalformedURLException notAFile) - { - throw new IllegalConfigurationException("Cannot convert " + urlString + " to a readable resource"); - } - - } - return new InputStreamReader(url.openStream()); - } - catch (IOException e) - { - throw new IllegalConfigurationException("Cannot convert " + urlString + " to a readable resource"); - } - } - - @Override - public void close() - { - //no-op - } - - @Override - public void onDelete() - { - //no-op - } - - @Override - public void onCreate() - { - if(_fileName != null) - { - //verify it is parsable - new PlainConfiguration(_fileName, _eventLogger).load(getReaderFromURLString(_fileName)); - } - } - - public Result getDefault() - { - return _ruleSet.getDefault(); - } - - /** - * Check if an operation is authorised by asking the configuration object about the access - * control rules granted to the current thread's {@link Subject}. If there is no current - * user the plugin will abstain. - */ - public Result authorise(Operation operation, ObjectType objectType, ObjectProperties properties) - { - InetAddress addressOfClient = null; - final Subject subject = Subject.getSubject(AccessController.getContext()); - - // Abstain if there is no subject/principal associated with this thread - if (subject == null || subject.getPrincipals().size() == 0) - { - return Result.ABSTAIN; - } - - Set principals = subject.getPrincipals(ConnectionPrincipal.class); - if(!principals.isEmpty()) - { - SocketAddress address = principals.iterator().next().getConnection().getRemoteAddress(); - if(address instanceof InetSocketAddress) - { - addressOfClient = ((InetSocketAddress) address).getAddress(); - } - } - - if(_logger.isDebugEnabled()) - { - _logger.debug("Checking " + operation + " " + objectType + " " + ObjectUtils.defaultIfNull(addressOfClient, "")); - } - - try - { - return _ruleSet.check(subject, operation, objectType, properties, addressOfClient); - } - catch(Exception e) - { - _logger.error("Unable to check " + operation + " " + objectType + " " + ObjectUtils.defaultIfNull(addressOfClient, ""), e); - return Result.DENIED; - } - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/main/resources/acl.xsd b/qpid/java/broker-plugins/access-control/src/main/resources/acl.xsd deleted file mode 100644 index 9a165b50b8..0000000000 --- a/qpid/java/broker-plugins/access-control/src/main/resources/acl.xsd +++ /dev/null @@ -1,29 +0,0 @@ - - - - - diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/AclActionTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/AclActionTest.java deleted file mode 100644 index 14620cff70..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/AclActionTest.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.access.config; - -import static org.mockito.Mockito.*; - -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.firewall.FirewallRule; - -import junit.framework.TestCase; - -public class AclActionTest extends TestCase -{ - public void testEqualsAndHashCode() - { - AclRulePredicates predicates = createAclRulePredicates(); - ObjectType objectType = ObjectType.EXCHANGE; - Operation operation = Operation.ACCESS; - - AclAction aclAction = new AclAction(operation, objectType, predicates); - AclAction equalAclAction = new AclAction(operation, objectType, predicates); - - assertTrue(aclAction.equals(aclAction)); - assertTrue(aclAction.equals(equalAclAction)); - assertTrue(equalAclAction.equals(aclAction)); - - assertTrue(aclAction.hashCode() == equalAclAction.hashCode()); - - assertFalse("Different operation should cause aclActions to be unequal", - aclAction.equals(new AclAction(Operation.BIND, objectType, predicates))); - - assertFalse("Different operation type should cause aclActions to be unequal", - aclAction.equals(new AclAction(operation, ObjectType.GROUP, predicates))); - - assertFalse("Different predicates should cause aclActions to be unequal", - aclAction.equals(new AclAction(operation, objectType, createAclRulePredicates()))); - - } - - private AclRulePredicates createAclRulePredicates() - { - AclRulePredicates predicates = mock(AclRulePredicates.class); - when(predicates.getFirewallRule()).thenReturn(mock(FirewallRule.class)); - when(predicates.getObjectProperties()).thenReturn(mock(ObjectProperties.class)); - return predicates; - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/AclRulePredicatesTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/AclRulePredicatesTest.java deleted file mode 100644 index 93b765d0fb..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/AclRulePredicatesTest.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.config; - -import static org.apache.qpid.server.security.access.ObjectProperties.Property.*; - -import org.apache.qpid.server.security.access.firewall.FirewallRule; -import org.apache.qpid.server.security.access.firewall.FirewallRuleFactory; - -import static org.mockito.Mockito.*; - -import junit.framework.TestCase; - -public class AclRulePredicatesTest extends TestCase -{ - private AclRulePredicates _aclRulePredicates = new AclRulePredicates(); - private FirewallRuleFactory _firewallRuleFactory = mock(FirewallRuleFactory.class); - - @Override - protected void setUp() throws Exception - { - _aclRulePredicates.setFirewallRuleFactory(_firewallRuleFactory); - - when(_firewallRuleFactory.createForHostname((String[]) any())).thenReturn(mock(FirewallRule.class)); - when(_firewallRuleFactory.createForNetwork((String[]) any())).thenReturn(mock(FirewallRule.class)); - } - - public void testParse() - { - String name = "name"; - String className = "class"; - - _aclRulePredicates.parse(NAME.name(), name); - _aclRulePredicates.parse(CLASS.name(), className); - - assertEquals(name, _aclRulePredicates.getObjectProperties().get(NAME)); - assertEquals(className, _aclRulePredicates.getObjectProperties().get(CLASS)); - } - - public void testParseHostnameFirewallRule() - { - String hostname = "hostname1,hostname2"; - _aclRulePredicates.parse(FROM_HOSTNAME.name(), hostname); - - verify(_firewallRuleFactory).createForHostname(new String[] {"hostname1", "hostname2"}); - } - - public void testParseNetworkFirewallRule() - { - _aclRulePredicates.setFirewallRuleFactory(_firewallRuleFactory); - - String networks = "network1,network2"; - _aclRulePredicates.parse(FROM_NETWORK.name(), networks); - - verify(_firewallRuleFactory).createForNetwork(new String[] {"network1", "network2"}); - } - - public void testParseThrowsExceptionIfBothHostnameAndNetworkSpecified() - { - _aclRulePredicates.parse(FROM_NETWORK.name(), "network1,network2"); - try - { - _aclRulePredicates.parse(FROM_HOSTNAME.name(), "hostname1,hostname2"); - fail("Exception not thrown"); - } - catch(IllegalStateException e) - { - // pass - } - } -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/ActionTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/ActionTest.java deleted file mode 100644 index 00e06106bf..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/ActionTest.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.config; - -import static org.mockito.Mockito.*; - -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 junit.framework.TestCase; - -public class ActionTest extends TestCase -{ - private ObjectProperties _properties1 = mock(ObjectProperties.class); - private ObjectProperties _properties2 = mock(ObjectProperties.class); - - public void testMatchesReturnsTrueForMatchingActions() - { - when(_properties1.matches(_properties2)).thenReturn(true); - - assertMatches( - new Action(Operation.CONSUME, ObjectType.QUEUE, _properties1), - new Action(Operation.CONSUME, ObjectType.QUEUE, _properties2)); - } - - public void testMatchesReturnsFalseWhenOperationsDiffer() - { - assertDoesntMatch( - new Action(Operation.CONSUME, ObjectType.QUEUE, _properties1), - new Action(Operation.CREATE, ObjectType.QUEUE, _properties1)); - } - - public void testMatchesReturnsFalseWhenOperationTypesDiffer() - { - assertDoesntMatch( - new Action(Operation.CREATE, ObjectType.QUEUE, _properties1), - new Action(Operation.CREATE, ObjectType.EXCHANGE, _properties1)); - } - - public void testMatchesReturnsFalseWhenOperationPropertiesDiffer() - { - assertDoesntMatch( - new Action(Operation.CREATE, ObjectType.QUEUE, _properties1), - new Action(Operation.CREATE, ObjectType.QUEUE, _properties2)); - } - - public void testMatchesReturnsFalseWhenMyOperationPropertiesIsNull() - { - assertDoesntMatch( - new Action(Operation.CREATE, ObjectType.QUEUE, (ObjectProperties)null), - new Action(Operation.CREATE, ObjectType.QUEUE, _properties1)); - } - - public void testMatchesReturnsFalseWhenOtherOperationPropertiesIsNull() - { - assertDoesntMatch( - new Action(Operation.CREATE, ObjectType.QUEUE, _properties1), - new Action(Operation.CREATE, ObjectType.QUEUE, (ObjectProperties)null)); - } - - public void testMatchesReturnsTrueWhenBothOperationPropertiesAreNull() - { - assertMatches( - new Action(Operation.CREATE, ObjectType.QUEUE, (ObjectProperties)null), - new Action(Operation.CREATE, ObjectType.QUEUE, (ObjectProperties)null)); - } - - private void assertMatches(Action action1, Action action2) - { - assertTrue(action1 + " should match " + action2, action1.matches(action2)); - } - - private void assertDoesntMatch(Action action1, Action action2) - { - assertFalse(action1 + " should not match " + action2, action1.matches(action2)); - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/ClientActionTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/ClientActionTest.java deleted file mode 100644 index ae5d3fda74..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/ClientActionTest.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.security.access.config; - -import static org.mockito.Mockito.*; - -import java.net.InetAddress; - -import org.apache.qpid.server.security.access.firewall.FirewallRule; - -import junit.framework.TestCase; - -public class ClientActionTest extends TestCase -{ - private Action _action = mock(Action.class); - private AclAction _ruleAction = mock(AclAction.class); - private InetAddress _addressOfClient = mock(InetAddress.class); - - private ClientAction _clientAction = new ClientAction(_action); - - public void testMatches_returnsTrueWhenActionsMatchAndNoFirewallRule() - { - when(_action.matches(any(Action.class))).thenReturn(true); - when(_ruleAction.getFirewallRule()).thenReturn(null); - - assertTrue(_clientAction.matches(_ruleAction, _addressOfClient)); - } - - public void testMatches_returnsFalseWhenActionsDontMatch() - { - FirewallRule firewallRule = mock(FirewallRule.class); - when(firewallRule.matches(_addressOfClient)).thenReturn(true); - - when(_action.matches(any(Action.class))).thenReturn(false); - when(_ruleAction.getFirewallRule()).thenReturn(firewallRule); - - assertFalse(_clientAction.matches(_ruleAction, _addressOfClient)); - } - - public void testMatches_returnsTrueWhenActionsAndFirewallRuleMatch() - { - FirewallRule firewallRule = mock(FirewallRule.class); - when(firewallRule.matches(_addressOfClient)).thenReturn(true); - - when(_action.matches(any(Action.class))).thenReturn(true); - when(_ruleAction.getFirewallRule()).thenReturn(firewallRule); - - assertTrue(_clientAction.matches(_ruleAction, _addressOfClient)); - } - - public void testMatches_ignoresFirewallRuleIfClientAddressIsNull() - { - FirewallRule firewallRule = mock(FirewallRule.class); - - when(_action.matches(any(Action.class))).thenReturn(true); - when(_ruleAction.getFirewallRule()).thenReturn(firewallRule); - - assertTrue(_clientAction.matches(_ruleAction, null)); - - verifyZeroInteractions(firewallRule); - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/PlainConfigurationTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/PlainConfigurationTest.java deleted file mode 100644 index 76435cbae4..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/PlainConfigurationTest.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.server.security.access.config; - -import static org.mockito.Mockito.mock; - -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.PrintWriter; -import java.util.Map; - -import junit.framework.TestCase; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.logging.EventLoggerProvider; -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectProperties.Property; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; - -public class PlainConfigurationTest extends TestCase -{ - private PlainConfiguration 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 - PlainConfiguration configFile = new PlainConfiguration(acl.getName(), mock(EventLoggerProvider.class)); - configFile.load(new FileReader(acl)); - return configFile; - } - - public void testACLFileSyntaxContinuation() throws Exception - { - try - { - writeACLConfig("ACL ALLOW ALL \\ ALL"); - fail("fail"); - } - catch (IllegalConfigurationException 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 (IllegalConfigurationException 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 testACLFileSyntaxNotEnoughACL() throws Exception - { - try - { - writeACLConfig("ACL ALLOW"); - fail("fail"); - } - catch (IllegalConfigurationException ce) - { - assertEquals(String.format(PlainConfiguration.NOT_ENOUGH_ACL_MSG, 1), ce.getMessage()); - } - } - - public void testACLFileSyntaxNotEnoughConfig() throws Exception - { - try - { - writeACLConfig("CONFIG"); - fail("fail"); - } - catch (IllegalConfigurationException ce) - { - assertEquals(String.format(PlainConfiguration.NOT_ENOUGH_TOKENS_MSG, 1), ce.getMessage()); - } - } - - public void testACLFileSyntaxNotEnough() throws Exception - { - try - { - writeACLConfig("INVALID"); - fail("fail"); - } - catch (IllegalConfigurationException 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 (IllegalConfigurationException 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 (IllegalConfigurationException 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 (IllegalConfigurationException ce) - { - assertEquals(String.format(PlainConfiguration.PROPERTY_NO_VALUE_MSG, 1), ce.getMessage()); - } - } - - /** - * Tests interpretation of an acl rule with no object properties. - * - */ - public void testValidRule() throws Exception - { - final PlainConfiguration config = writeACLConfig("ACL DENY-LOG user1 ACCESS VIRTUALHOST"); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "user1", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.ACCESS, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.VIRTUALHOST, rule.getAction().getObjectType()); - assertEquals("Rule has unexpected object properties", ObjectProperties.EMPTY, rule.getAction().getProperties()); - } - - /** - * Tests interpretation of an acl rule with object properties quoted in single quotes. - */ - public void testValidRuleWithSingleQuotedProperty() throws Exception - { - final PlainConfiguration config = writeACLConfig("ACL ALLOW all CREATE EXCHANGE name = \'value\'"); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "all", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.CREATE, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.EXCHANGE, rule.getAction().getObjectType()); - final ObjectProperties expectedProperties = new ObjectProperties(); - expectedProperties.setName("value"); - assertEquals("Rule has unexpected object properties", expectedProperties, rule.getAction().getProperties()); - } - - /** - * Tests interpretation of an acl rule with object properties quoted in double quotes. - */ - public void testValidRuleWithDoubleQuotedProperty() throws Exception - { - final PlainConfiguration config = writeACLConfig("ACL ALLOW all CREATE EXCHANGE name = \"value\""); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "all", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.CREATE, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.EXCHANGE, rule.getAction().getObjectType()); - final ObjectProperties expectedProperties = new ObjectProperties(); - expectedProperties.setName("value"); - assertEquals("Rule has unexpected object properties", expectedProperties, rule.getAction().getProperties()); - } - - /** - * Tests interpretation of an acl rule with many object properties. - */ - public void testValidRuleWithManyProperties() throws Exception - { - final PlainConfiguration config = writeACLConfig("ACL ALLOW admin DELETE QUEUE name=name1 owner = owner1"); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "admin", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.DELETE, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.QUEUE, rule.getAction().getObjectType()); - final ObjectProperties expectedProperties = new ObjectProperties(); - expectedProperties.setName("name1"); - expectedProperties.put(Property.OWNER, "owner1"); - assertEquals("Rule has unexpected operation", expectedProperties, rule.getAction().getProperties()); - } - - /** - * Tests interpretation of an acl rule with object properties containing wildcards. Values containing - * hashes must be quoted otherwise they are interpreted as comments. - */ - public void testValidRuleWithWildcardProperties() throws Exception - { - final PlainConfiguration config = writeACLConfig("ACL ALLOW all CREATE EXCHANGE routingKey = \'news.#\'", - "ACL ALLOW all CREATE EXCHANGE routingKey = \'news.co.#\'", - "ACL ALLOW all CREATE EXCHANGE routingKey = *.co.medellin"); - final RuleSet rs = config.getConfiguration(); - assertEquals(3, rs.getRuleCount()); - - final Map rules = rs.getAllRules(); - assertEquals(3, rules.size()); - final Rule rule1 = rules.get(0); - assertEquals("Rule has unexpected identity", "all", rule1.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.CREATE, rule1.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.EXCHANGE, rule1.getAction().getObjectType()); - final ObjectProperties expectedProperties1 = new ObjectProperties(); - expectedProperties1.put(Property.ROUTING_KEY,"news.#"); - assertEquals("Rule has unexpected object properties", expectedProperties1, rule1.getAction().getProperties()); - - final Rule rule2 = rules.get(10); - final ObjectProperties expectedProperties2 = new ObjectProperties(); - expectedProperties2.put(Property.ROUTING_KEY,"news.co.#"); - assertEquals("Rule has unexpected object properties", expectedProperties2, rule2.getAction().getProperties()); - - final Rule rule3 = rules.get(20); - final ObjectProperties expectedProperties3 = new ObjectProperties(); - expectedProperties3.put(Property.ROUTING_KEY,"*.co.medellin"); - assertEquals("Rule has unexpected object properties", expectedProperties3, rule3.getAction().getProperties()); - } - - /** - * Tests that rules are case insignificant. - */ - public void testMixedCaseRuleInterpretation() throws Exception - { - final PlainConfiguration config = writeACLConfig("AcL deny-LOG User1 BiND Exchange Name=AmQ.dIrect"); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "User1", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.BIND, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.EXCHANGE, rule.getAction().getObjectType()); - final ObjectProperties expectedProperties = new ObjectProperties("AmQ.dIrect"); - assertEquals("Rule has unexpected object properties", expectedProperties, rule.getAction().getProperties()); - } - - /** - * Tests whitespace is supported. Note that currently the Java implementation permits comments to - * be introduced anywhere in the ACL, whereas the C++ supports only whitespace at the beginning of - * of line. - */ - public void testCommentsSupported() throws Exception - { - final PlainConfiguration config = writeACLConfig("#Comment", - "ACL DENY-LOG user1 ACCESS VIRTUALHOST # another comment", - " # final comment with leading whitespace"); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "user1", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.ACCESS, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.VIRTUALHOST, rule.getAction().getObjectType()); - assertEquals("Rule has unexpected object properties", ObjectProperties.EMPTY, rule.getAction().getProperties()); - } - - /** - * Tests interpretation of an acl rule using mixtures of tabs/spaces as token separators. - * - */ - public void testWhitespace() throws Exception - { - final PlainConfiguration config = writeACLConfig("ACL\tDENY-LOG\t\t user1\t \tACCESS VIRTUALHOST"); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "user1", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.ACCESS, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.VIRTUALHOST, rule.getAction().getObjectType()); - assertEquals("Rule has unexpected object properties", ObjectProperties.EMPTY, rule.getAction().getProperties()); - } - - /** - * Tests interpretation of an acl utilising line continuation. - */ - public void testLineContinuation() throws Exception - { - final PlainConfiguration config = writeACLConfig("ACL DENY-LOG user1 \\", - "ACCESS VIRTUALHOST"); - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", "user1", rule.getIdentity()); - assertEquals("Rule has unexpected operation", Operation.ACCESS, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", ObjectType.VIRTUALHOST, rule.getAction().getObjectType()); - assertEquals("Rule has unexpected object properties", ObjectProperties.EMPTY, rule.getAction().getProperties()); - } - - public void testUserRuleParsing() throws Exception - { - validateRule(writeACLConfig("ACL ALLOW user1 CREATE USER"), - "user1", Operation.CREATE, ObjectType.USER, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 CREATE USER name=\"otherUser\""), - "user1", Operation.CREATE, ObjectType.USER, new ObjectProperties("otherUser")); - - validateRule(writeACLConfig("ACL ALLOW user1 DELETE USER"), - "user1", Operation.DELETE, ObjectType.USER, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 DELETE USER name=\"otherUser\""), - "user1", Operation.DELETE, ObjectType.USER, new ObjectProperties("otherUser")); - - validateRule(writeACLConfig("ACL ALLOW user1 UPDATE USER"), - "user1", Operation.UPDATE, ObjectType.USER, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 UPDATE USER name=\"otherUser\""), - "user1", Operation.UPDATE, ObjectType.USER, new ObjectProperties("otherUser")); - - validateRule(writeACLConfig("ACL ALLOW user1 ALL USER"), - "user1", Operation.ALL, ObjectType.USER, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 ALL USER name=\"otherUser\""), - "user1", Operation.ALL, ObjectType.USER, new ObjectProperties("otherUser")); - } - - public void testGroupRuleParsing() throws Exception - { - validateRule(writeACLConfig("ACL ALLOW user1 CREATE GROUP"), - "user1", Operation.CREATE, ObjectType.GROUP, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 CREATE GROUP name=\"groupName\""), - "user1", Operation.CREATE, ObjectType.GROUP, new ObjectProperties("groupName")); - - validateRule(writeACLConfig("ACL ALLOW user1 DELETE GROUP"), - "user1", Operation.DELETE, ObjectType.GROUP, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 DELETE GROUP name=\"groupName\""), - "user1", Operation.DELETE, ObjectType.GROUP, new ObjectProperties("groupName")); - - validateRule(writeACLConfig("ACL ALLOW user1 UPDATE GROUP"), - "user1", Operation.UPDATE, ObjectType.GROUP, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 UPDATE GROUP name=\"groupName\""), - "user1", Operation.UPDATE, ObjectType.GROUP, new ObjectProperties("groupName")); - - validateRule(writeACLConfig("ACL ALLOW user1 ALL GROUP"), - "user1", Operation.ALL, ObjectType.GROUP, ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 ALL GROUP name=\"groupName\""), - "user1", Operation.ALL, ObjectType.GROUP, new ObjectProperties("groupName")); - } - - /** explicitly test for exception indicating that this functionality has been moved to Group Providers */ - public void testGroupDefinitionThrowsException() throws Exception - { - try - { - writeACLConfig("GROUP group1 bob alice"); - fail("Expected exception not thrown"); - } - catch(IllegalConfigurationException e) - { - assertTrue(e.getMessage().contains("GROUP keyword not supported")); - } - } - - public void testManagementRuleParsing() throws Exception - { - validateRule(writeACLConfig("ACL ALLOW user1 ALL MANAGEMENT"), - "user1", Operation.ALL, ObjectType.MANAGEMENT, ObjectProperties.EMPTY); - - validateRule(writeACLConfig("ACL ALLOW user1 ACCESS MANAGEMENT"), - "user1", Operation.ACCESS, ObjectType.MANAGEMENT, ObjectProperties.EMPTY); - } - - public void testBrokerRuleParsing() throws Exception - { - validateRule(writeACLConfig("ACL ALLOW user1 CONFIGURE BROKER"), "user1", Operation.CONFIGURE, ObjectType.BROKER, - ObjectProperties.EMPTY); - validateRule(writeACLConfig("ACL ALLOW user1 ALL BROKER"), "user1", Operation.ALL, ObjectType.BROKER, ObjectProperties.EMPTY); - } - - private void validateRule(final PlainConfiguration config, String username, Operation operation, ObjectType objectType, ObjectProperties objectProperties) - { - final RuleSet rs = config.getConfiguration(); - assertEquals(1, rs.getRuleCount()); - - final Map rules = rs.getAllRules(); - assertEquals(1, rules.size()); - final Rule rule = rules.get(0); - assertEquals("Rule has unexpected identity", username, rule.getIdentity()); - assertEquals("Rule has unexpected operation", operation, rule.getAction().getOperation()); - assertEquals("Rule has unexpected operation", objectType, rule.getAction().getObjectType()); - assertEquals("Rule has unexpected object properties", objectProperties, rule.getAction().getProperties()); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/RuleTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/RuleTest.java deleted file mode 100644 index 2ae7759679..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/config/RuleTest.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.access.config; - -import static org.mockito.Mockito.*; - -import org.apache.qpid.server.security.access.Permission; - -import junit.framework.TestCase; - -public class RuleTest extends TestCase -{ - public void testEqualsAndHashCode() - { - AclAction aclAction = mock(AclAction.class); - String identity = "identity"; - Permission allow = Permission.ALLOW; - - Rule rule = new Rule(identity, aclAction, allow); - Rule equalRule = new Rule(identity, aclAction, allow); - - assertTrue(rule.equals(rule)); - assertTrue(rule.equals(equalRule)); - assertTrue(equalRule.equals(rule)); - - assertTrue(rule.hashCode() == equalRule.hashCode()); - - assertFalse("Different identity should cause rules to be unequal", - rule.equals(new Rule("identity2", aclAction, allow))); - - assertFalse("Different action should cause rules to be unequal", - rule.equals(new Rule(identity, mock(AclAction.class), allow))); - - assertFalse("Different permission should cause rules to be unequal", - rule.equals(new Rule(identity, aclAction, Permission.DENY))); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/firewall/HostnameFirewallRuleTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/firewall/HostnameFirewallRuleTest.java deleted file mode 100644 index d2beebfb0f..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/firewall/HostnameFirewallRuleTest.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.firewall; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.net.InetAddress; - -import org.apache.qpid.server.security.access.firewall.HostnameFirewallRule; - -import junit.framework.TestCase; - -public class HostnameFirewallRuleTest extends TestCase -{ - private InetAddress _addressNotInRule; - - private HostnameFirewallRule _HostnameFirewallRule; - - @Override - protected void setUp() throws Exception - { - _addressNotInRule = InetAddress.getByName("127.0.0.1"); - } - - public void testSingleHostname() throws Exception - { - String hostnameInRule = "hostnameInRule"; - InetAddress addressWithMatchingHostname = mock(InetAddress.class); - when(addressWithMatchingHostname.getCanonicalHostName()).thenReturn(hostnameInRule); - - _HostnameFirewallRule = new HostnameFirewallRule(hostnameInRule); - - assertFalse(_HostnameFirewallRule.matches(_addressNotInRule)); - assertTrue(_HostnameFirewallRule.matches(addressWithMatchingHostname)); - } - - public void testSingleHostnameWildcard() throws Exception - { - String hostnameInRule = ".*FOO.*"; - InetAddress addressWithMatchingHostname = mock(InetAddress.class); - when(addressWithMatchingHostname.getCanonicalHostName()).thenReturn("xxFOOxx"); - - _HostnameFirewallRule = new HostnameFirewallRule(hostnameInRule); - - assertFalse(_HostnameFirewallRule.matches(_addressNotInRule)); - assertTrue(_HostnameFirewallRule.matches(addressWithMatchingHostname)); - } - - public void testMultipleHostnames() throws Exception - { - String[] hostnamesInRule = new String[] {"hostnameInRule1", "hostnameInRule2"}; - - _HostnameFirewallRule = new HostnameFirewallRule(hostnamesInRule); - - assertFalse(_HostnameFirewallRule.matches(_addressNotInRule)); - for (String hostnameInRule : hostnamesInRule) - { - InetAddress addressWithMatchingHostname = mock(InetAddress.class); - when(addressWithMatchingHostname.getCanonicalHostName()).thenReturn(hostnameInRule); - - assertTrue(_HostnameFirewallRule.matches(addressWithMatchingHostname)); - } - } - - public void testEqualsAndHashCode() - { - String hostname1 = "hostname1"; - String hostname2 = "hostname2"; - - HostnameFirewallRule rule = new HostnameFirewallRule(hostname1, hostname2); - HostnameFirewallRule equalRule = new HostnameFirewallRule(hostname1, hostname2); - - assertTrue(rule.equals(rule)); - assertTrue(rule.equals(equalRule)); - assertTrue(equalRule.equals(rule)); - - assertTrue(rule.hashCode() == equalRule.hashCode()); - - assertFalse("Different hostnames should cause rules to be unequal", - rule.equals(new HostnameFirewallRule(hostname1, "different-hostname"))); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/firewall/NetworkFirewallRuleTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/firewall/NetworkFirewallRuleTest.java deleted file mode 100644 index e521039db2..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/firewall/NetworkFirewallRuleTest.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.server.security.access.firewall; - -import java.net.InetAddress; - -import org.apache.qpid.server.security.access.firewall.NetworkFirewallRule; - -import junit.framework.TestCase; - -public class NetworkFirewallRuleTest extends TestCase -{ - private static final String LOCALHOST_IP = "127.0.0.1"; - private static final String OTHER_IP_1 = "192.168.23.1"; - private static final String OTHER_IP_2 = "192.168.23.2"; - - private InetAddress _addressNotInRule; - - private NetworkFirewallRule _networkFirewallRule; - - @Override - protected void setUp() throws Exception - { - _addressNotInRule = InetAddress.getByName(LOCALHOST_IP); - } - - public void testIpRule() throws Exception - { - String ipAddressInRule = OTHER_IP_1; - - _networkFirewallRule = new NetworkFirewallRule(ipAddressInRule); - - assertFalse(_networkFirewallRule.matches(_addressNotInRule)); - assertTrue(_networkFirewallRule.matches(InetAddress.getByName(ipAddressInRule))); - } - - public void testNetMask() throws Exception - { - String ipAddressInRule = "192.168.23.0/24"; - _networkFirewallRule = new NetworkFirewallRule(ipAddressInRule); - - assertFalse(_networkFirewallRule.matches(InetAddress.getByName("192.168.24.1"))); - assertTrue(_networkFirewallRule.matches(InetAddress.getByName("192.168.23.0"))); - assertTrue(_networkFirewallRule.matches(InetAddress.getByName("192.168.23.255"))); - } - - public void testWildcard() throws Exception - { - // Test xxx.xxx.* - - assertFalse(new NetworkFirewallRule("192.168.*") - .matches(InetAddress.getByName("192.169.1.0"))); - - assertTrue(new NetworkFirewallRule("192.168.*") - .matches(InetAddress.getByName("192.168.1.0"))); - - assertTrue(new NetworkFirewallRule("192.168.*") - .matches(InetAddress.getByName("192.168.255.255"))); - - // Test xxx.xxx.xxx.* - - assertFalse(new NetworkFirewallRule("192.168.1.*") - .matches(InetAddress.getByName("192.169.2.0"))); - - assertTrue(new NetworkFirewallRule("192.168.1.*") - .matches(InetAddress.getByName("192.168.1.0"))); - - assertTrue(new NetworkFirewallRule("192.168.1.*") - .matches(InetAddress.getByName("192.168.1.255"))); - } - - public void testMultipleNetworks() throws Exception - { - String[] ipAddressesInRule = new String[] {OTHER_IP_1, OTHER_IP_2}; - - _networkFirewallRule = new NetworkFirewallRule(ipAddressesInRule); - - assertFalse(_networkFirewallRule.matches(_addressNotInRule)); - for (String ipAddressInRule : ipAddressesInRule) - { - assertTrue(_networkFirewallRule.matches(InetAddress.getByName(ipAddressInRule))); - } - } - - public void testEqualsAndHashCode() - { - NetworkFirewallRule rule = new NetworkFirewallRule(LOCALHOST_IP, OTHER_IP_1); - NetworkFirewallRule equalRule = new NetworkFirewallRule(LOCALHOST_IP, OTHER_IP_1); - - assertTrue(rule.equals(rule)); - assertTrue(rule.equals(equalRule)); - assertTrue(equalRule.equals(rule)); - - assertTrue(rule.hashCode() == equalRule.hashCode()); - - assertFalse("Different networks should cause rules to be unequal", - rule.equals(new NetworkFirewallRule(LOCALHOST_IP, OTHER_IP_2))); - } -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderFactoryTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderFactoryTest.java deleted file mode 100644 index c51ea64d9c..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderFactoryTest.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.security.access.plugins; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import java.util.regex.Pattern; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.configuration.updater.CurrentThreadTaskExecutor; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.model.AccessControlProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.BrokerModel; -import org.apache.qpid.server.model.ConfiguredObjectFactoryImpl; -import org.apache.qpid.server.security.access.FileAccessControlProviderConstants; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.test.utils.TestFileUtils; - -public class ACLFileAccessControlProviderFactoryTest extends QpidTestCase -{ - private Broker _broker; - private ConfiguredObjectFactoryImpl _objectFactory; - - @Override - public void setUp() throws Exception - { - super.setUp(); - _broker = mock(Broker.class); - _objectFactory = new ConfiguredObjectFactoryImpl(BrokerModel.getInstance()); - - when(_broker.getObjectFactory()).thenReturn(_objectFactory); - when(_broker.getModel()).thenReturn(_objectFactory.getModel()); - when(_broker.getCategoryClass()).thenReturn(Broker.class); - TaskExecutor taskExecutor = new CurrentThreadTaskExecutor(); - taskExecutor.start(); - when(_broker.getTaskExecutor()).thenReturn(taskExecutor); - when(_broker.getChildExecutor()).thenReturn(taskExecutor); - - } - - public void testCreateInstanceWhenAclFileIsNotPresent() - { - Map attributes = new HashMap(); - attributes.put(AccessControlProvider.ID, UUID.randomUUID()); - attributes.put(AccessControlProvider.NAME, "acl"); - attributes.put(AccessControlProvider.TYPE, FileAccessControlProviderConstants.ACL_FILE_PROVIDER_TYPE); - - try - { - AccessControlProvider acl = _objectFactory.create(AccessControlProvider.class, attributes, _broker); - fail("ACL was created without a configuration file path specified"); - } - catch(IllegalArgumentException e) - { - // pass - } - } - - - public void testCreateInstanceWhenAclFileIsSpecified() - { - File aclFile = TestFileUtils.createTempFile(this, ".acl", "ACL ALLOW all all"); - Map attributes = new HashMap(); - attributes.put(AccessControlProvider.ID, UUID.randomUUID()); - attributes.put(AccessControlProvider.NAME, "acl"); - attributes.put(AccessControlProvider.TYPE, FileAccessControlProviderConstants.ACL_FILE_PROVIDER_TYPE); - attributes.put(FileAccessControlProviderConstants.PATH, aclFile.getAbsolutePath()); - AccessControlProvider acl = _objectFactory.create(AccessControlProvider.class, attributes, _broker); - acl.getAccessControl().open(); - - assertNotNull("ACL was not created from acl file: " + aclFile.getAbsolutePath(), acl); - } - - public void testCreateInstanceWhenAclFileIsSpecifiedButDoesNotExist() - { - File aclFile = new File(TMP_FOLDER, "my-non-existing-acl-" + System.currentTimeMillis()); - assertFalse("ACL file " + aclFile.getAbsolutePath() + " actually exists but should not", aclFile.exists()); - Map attributes = new HashMap(); - attributes.put(AccessControlProvider.ID, UUID.randomUUID()); - attributes.put(AccessControlProvider.NAME, "acl"); - attributes.put(AccessControlProvider.TYPE, FileAccessControlProviderConstants.ACL_FILE_PROVIDER_TYPE); - attributes.put(FileAccessControlProviderConstants.PATH, aclFile.getAbsolutePath()); - try - { - AccessControlProvider control = _objectFactory.create(AccessControlProvider.class, attributes, _broker); - control.getAccessControl().open(); - fail("It should not be possible to create and initialise ACL with non existing file"); - } - catch (IllegalConfigurationException e) - { - assertTrue("Unexpected exception message: " + e.getMessage(), Pattern.matches("Cannot convert .* to a readable resource", e.getMessage())); - } - } -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderImplTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderImplTest.java deleted file mode 100644 index abe8c6fd9f..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/ACLFileAccessControlProviderImplTest.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.access.plugins; - - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.configuration.updater.CurrentThreadTaskExecutor; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.BrokerModel; -import org.apache.qpid.server.model.Model; -import org.apache.qpid.test.utils.QpidTestCase; - -public class ACLFileAccessControlProviderImplTest extends QpidTestCase -{ - private TaskExecutor _taskExecutor; - private Model _model; - private Broker _broker; - - public void setUp() throws Exception - { - super.setUp(); - _taskExecutor = CurrentThreadTaskExecutor.newStartedInstance(); - _model = BrokerModel.getInstance(); - - _broker = mock(Broker.class); - when(_broker.getTaskExecutor()).thenReturn(_taskExecutor); - when(_broker.getChildExecutor()).thenReturn(_taskExecutor); - when(_broker.getModel()).thenReturn(_model); - when(_broker.getId()).thenReturn(UUID.randomUUID()); - } - - public void testValidationOnCreateWithNonExistingACLFile() - { - Map attributes = new HashMap<>(); - String aclFilePath = new File(TMP_FOLDER, "test_" + getTestName() + System.nanoTime() + ".acl").getAbsolutePath(); - - attributes.put("path", aclFilePath); - attributes.put(ACLFileAccessControlProvider.NAME, getTestName()); - - - ACLFileAccessControlProviderImpl aclProvider = new ACLFileAccessControlProviderImpl(attributes, _broker); - try - { - aclProvider.create(); - fail("Exception is expected on validation with non-existing ACL file"); - } - catch (IllegalConfigurationException e) - { - assertEquals("Unexpected exception message:" + e.getMessage(), String.format("Cannot convert %s to a readable resource", aclFilePath ), e.getMessage()); - } - } - -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/DefaultAccessControlTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/DefaultAccessControlTest.java deleted file mode 100644 index 072bd6a87f..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/DefaultAccessControlTest.java +++ /dev/null @@ -1,471 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.security.PrivilegedAction; -import java.security.PrivilegedExceptionAction; - -import javax.security.auth.Subject; - -import junit.framework.TestCase; - -import org.apache.qpid.server.connection.ConnectionPrincipal; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.EventLoggerProvider; -import org.apache.qpid.server.logging.UnitTestMessageLogger; -import org.apache.qpid.server.protocol.AMQConnectionModel; -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.Rule; -import org.apache.qpid.server.security.access.config.RuleSet; -import org.apache.qpid.server.security.auth.TestPrincipalUtils; - -/** - * In these tests, the ruleset is configured programmatically rather than from an external file. - * - * @see RuleSetTest - */ -public class DefaultAccessControlTest extends TestCase -{ - private static final String ALLOWED_GROUP = "allowed_group"; - private static final String DENIED_GROUP = "denied_group"; - - private DefaultAccessControl _plugin = null; // Class under test - private UnitTestMessageLogger _messageLogger; - private EventLogger _eventLogger; - - public void setUp() throws Exception - { - super.setUp(); - _messageLogger = new UnitTestMessageLogger(); - _eventLogger = new EventLogger(_messageLogger); - _plugin = null; - } - - private void setUpGroupAccessControl() - { - configureAccessControl(createGroupRuleSet()); - } - - private void configureAccessControl(final RuleSet rs) - { - _plugin = new DefaultAccessControl(rs); - } - - private RuleSet createGroupRuleSet() - { - final EventLoggerProvider provider = mock(EventLoggerProvider.class); - when(provider.getEventLogger()).thenReturn(_eventLogger); - final RuleSet rs = new RuleSet(provider); - - // Rule expressed with username - rs.grant(0, "user1", Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - // Rules expressed with groups - rs.grant(1, ALLOWED_GROUP, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - rs.grant(2, DENIED_GROUP, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - // Catch all rule - rs.grant(3, Rule.ALL, Permission.DENY_LOG, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - - return rs; - } - - /** - * ACL plugin must always abstain if there is no subject attached to the thread. - */ - public void testNoSubjectAlwaysAbstains() - { - setUpGroupAccessControl(); - final Result result = _plugin.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(Result.ABSTAIN, result); - } - - /** - * Tests that an allow rule expressed with a username allows an operation performed by a thread running - * with the same username. - */ - public void testUsernameAllowsOperation() - { - setUpGroupAccessControl(); - Subject.doAs(TestPrincipalUtils.createTestSubject("user1"), new PrivilegedAction() - { - @Override - public Object run() - { - final Result result = _plugin.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(Result.ALLOWED, result); - return null; - } - }); - } - - /** - * Tests that an allow rule expressed with an ACL groupname allows an operation performed by a thread running - * by a user who belongs to the same group.. - */ - public void testGroupMembershipAllowsOperation() - { - setUpGroupAccessControl(); - - authoriseAndAssertResult(Result.ALLOWED, "member of allowed group", ALLOWED_GROUP); - authoriseAndAssertResult(Result.DENIED, "member of denied group", DENIED_GROUP); - authoriseAndAssertResult(Result.ALLOWED, "another member of allowed group", ALLOWED_GROUP); - } - - /** - * Tests that a deny rule expressed with a groupname denies an operation performed by a thread running - * by a user who belongs to the same group. - */ - public void testGroupMembershipDeniesOperation() - { - setUpGroupAccessControl(); - authoriseAndAssertResult(Result.DENIED, "user3", DENIED_GROUP); - } - - /** - * Tests that the catch all deny denies the operation and logs with the logging actor. - */ - public void testCatchAllRuleDeniesUnrecognisedUsername() - { - setUpGroupAccessControl(); - Subject.doAs(TestPrincipalUtils.createTestSubject("unknown", "unkgroup1", "unkgroup2"), - new PrivilegedAction() - { - @Override - public Object run() - { - assertEquals("Expecting zero messages before test", - 0, - _messageLogger.getLogMessages().size()); - final Result result = _plugin.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(Result.DENIED, result); - - assertEquals("Expecting one message before test", 1, _messageLogger.getLogMessages().size()); - assertTrue("Logged message does not contain expected string", - _messageLogger.messageContains(0, "ACL-1002")); - return null; - } - }); - - } - - /** - * Tests that a grant access method rule allows any access operation to be performed on any component - */ - public void testAuthoriseAccessMethodWhenAllAccessOperationsAllowedOnAllComponents() - { - final RuleSet rs = new RuleSet(mock(EventLoggerProvider.class)); - - // grant user4 access right on any method in any component - rs.grant(1, "user4", Permission.ALLOW, Operation.ACCESS, ObjectType.METHOD, new ObjectProperties(ObjectProperties.WILD_CARD)); - configureAccessControl(rs); - Subject.doAs(TestPrincipalUtils.createTestSubject("user4"), new PrivilegedAction() - { - @Override - public Object run() - { - ObjectProperties actionProperties = new ObjectProperties("getName"); - actionProperties.put(ObjectProperties.Property.COMPONENT, "Test"); - - final Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, actionProperties); - assertEquals(Result.ALLOWED, result); - return null; - } - }); - - } - - /** - * Tests that a grant access method rule allows any access operation to be performed on a specified component - */ - public void testAuthoriseAccessMethodWhenAllAccessOperationsAllowedOnSpecifiedComponent() - { - final RuleSet rs = new RuleSet(mock(EventLoggerProvider.class)); - - // grant user5 access right on any methods in "Test" component - ObjectProperties ruleProperties = new ObjectProperties(ObjectProperties.WILD_CARD); - ruleProperties.put(ObjectProperties.Property.COMPONENT, "Test"); - rs.grant(1, "user5", Permission.ALLOW, Operation.ACCESS, ObjectType.METHOD, ruleProperties); - configureAccessControl(rs); - Subject.doAs(TestPrincipalUtils.createTestSubject("user5"), new PrivilegedAction() - { - @Override - public Object run() - { - ObjectProperties actionProperties = new ObjectProperties("getName"); - actionProperties.put(ObjectProperties.Property.COMPONENT, "Test"); - Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, actionProperties); - assertEquals(Result.ALLOWED, result); - - actionProperties.put(ObjectProperties.Property.COMPONENT, "Test2"); - result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, actionProperties); - assertEquals(Result.DEFER, result); - return null; - } - }); - - - } - - public void testAccess() throws Exception - { - final Subject subject = TestPrincipalUtils.createTestSubject("user1"); - final String testVirtualHost = getName(); - final InetAddress inetAddress = InetAddress.getLocalHost(); - final InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, 1); - - AMQConnectionModel connectionModel = mock(AMQConnectionModel.class); - when(connectionModel.getRemoteAddress()).thenReturn(inetSocketAddress); - - subject.getPrincipals().add(new ConnectionPrincipal(connectionModel)); - - Subject.doAs(subject, new PrivilegedExceptionAction() - { - @Override - public Object run() throws Exception - { - RuleSet mockRuleSet = mock(RuleSet.class); - - DefaultAccessControl accessControl = new DefaultAccessControl(mockRuleSet); - - ObjectProperties properties = new ObjectProperties(testVirtualHost); - accessControl.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, properties); - - verify(mockRuleSet).check(subject, Operation.ACCESS, ObjectType.VIRTUALHOST, properties, inetAddress); - return null; - } - }); - - } - - public void testAccessIsDeniedIfRuleThrowsException() throws Exception - { - final Subject subject = TestPrincipalUtils.createTestSubject("user1"); - final InetAddress inetAddress = InetAddress.getLocalHost(); - final InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, 1); - - AMQConnectionModel connectionModel = mock(AMQConnectionModel.class); - when(connectionModel.getRemoteAddress()).thenReturn(inetSocketAddress); - - subject.getPrincipals().add(new ConnectionPrincipal(connectionModel)); - - Subject.doAs(subject, new PrivilegedExceptionAction() - { - @Override - public Object run() throws Exception - { - - - RuleSet mockRuleSet = mock(RuleSet.class); - when(mockRuleSet.check( - subject, - Operation.ACCESS, - ObjectType.VIRTUALHOST, - ObjectProperties.EMPTY, - inetAddress)).thenThrow(new RuntimeException()); - - DefaultAccessControl accessControl = new DefaultAccessControl(mockRuleSet); - Result result = accessControl.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - - assertEquals(Result.DENIED, result); - return null; - } - }); - - } - - - /** - * Tests that a grant access method rule allows any access operation to be performed on a specified component - */ - public void testAuthoriseAccessMethodWhenSpecifiedAccessOperationsAllowedOnSpecifiedComponent() - { - final RuleSet rs = new RuleSet(mock(EventLoggerProvider.class)); - - // grant user6 access right on "getAttribute" method in "Test" component - ObjectProperties ruleProperties = new ObjectProperties("getAttribute"); - ruleProperties.put(ObjectProperties.Property.COMPONENT, "Test"); - rs.grant(1, "user6", Permission.ALLOW, Operation.ACCESS, ObjectType.METHOD, ruleProperties); - configureAccessControl(rs); - Subject.doAs(TestPrincipalUtils.createTestSubject("user6"), new PrivilegedAction() - { - @Override - public Object run() - { - ObjectProperties properties = new ObjectProperties("getAttribute"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - properties.put(ObjectProperties.Property.COMPONENT, "Test2"); - result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.DEFER, result); - - properties = new ObjectProperties("getAttribute2"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.DEFER, result); - - return null; - } - }); - - } - - /** - * Tests that granting of all method rights on a method allows a specified operation to be performed on any component - */ - public void testAuthoriseAccessUpdateMethodWhenAllRightsGrantedOnSpecifiedMethodForAllComponents() - { - final RuleSet rs = new RuleSet(mock(EventLoggerProvider.class)); - - // grant user8 all rights on method queryNames in all component - rs.grant(1, "user8", Permission.ALLOW, Operation.ALL, ObjectType.METHOD, new ObjectProperties("queryNames")); - configureAccessControl(rs); - Subject.doAs(TestPrincipalUtils.createTestSubject("user8"), new PrivilegedAction() - { - @Override - public Object run() - { - ObjectProperties properties = new ObjectProperties(); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - properties.put(ObjectProperties.Property.NAME, "queryNames"); - - Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - result = _plugin.authorise(Operation.UPDATE, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - properties = new ObjectProperties("getAttribute"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - result = _plugin.authorise(Operation.UPDATE, ObjectType.METHOD, properties); - assertEquals(Result.DEFER, result); - - result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.DEFER, result); - return null; - } - }); - - - } - - /** - * Tests that granting of all method rights allows any operation to be performed on any component - */ - public void testAuthoriseAccessUpdateMethodWhenAllRightsGrantedOnAllMethodsInAllComponents() - { - final RuleSet rs = new RuleSet(mock(EventLoggerProvider.class)); - - // grant user9 all rights on any method in all component - rs.grant(1, "user9", Permission.ALLOW, Operation.ALL, ObjectType.METHOD, new ObjectProperties()); - configureAccessControl(rs); - Subject.doAs(TestPrincipalUtils.createTestSubject("user9"), new PrivilegedAction() - { - @Override - public Object run() - { - ObjectProperties properties = new ObjectProperties("queryNames"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - - Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - result = _plugin.authorise(Operation.UPDATE, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - properties = new ObjectProperties("getAttribute"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - result = _plugin.authorise(Operation.UPDATE, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - return null; - } - }); - - - } - - /** - * Tests that granting of access method rights with mask allows matching operations to be performed on the specified component - */ - public void testAuthoriseAccessMethodWhenMatchingAccessOperationsAllowedOnSpecifiedComponent() - { - final RuleSet rs = new RuleSet(mock(EventLoggerProvider.class)); - - // grant user9 all rights on "getAttribute*" methods in Test component - ObjectProperties ruleProperties = new ObjectProperties(); - ruleProperties.put(ObjectProperties.Property.COMPONENT, "Test"); - ruleProperties.put(ObjectProperties.Property.NAME, "getAttribute*"); - - rs.grant(1, "user9", Permission.ALLOW, Operation.ACCESS, ObjectType.METHOD, ruleProperties); - configureAccessControl(rs); - Subject.doAs(TestPrincipalUtils.createTestSubject("user9"), new PrivilegedAction() - { - @Override - public Object run() - { - ObjectProperties properties = new ObjectProperties("getAttributes"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - properties = new ObjectProperties("getAttribute"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.ALLOWED, result); - - properties = new ObjectProperties("getAttribut"); - properties.put(ObjectProperties.Property.COMPONENT, "Test"); - result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); - assertEquals(Result.DEFER, result); - return null; - } - }); - } - - private void authoriseAndAssertResult(final Result expectedResult, String userName, String... groups) - { - - Subject.doAs(TestPrincipalUtils.createTestSubject(userName, groups), new PrivilegedAction() - { - @Override - public Object run() - { - Result result = _plugin.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(expectedResult, result); - return null; - } - }); - - } -} diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/RuleSetTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/RuleSetTest.java deleted file mode 100644 index 5301d2e49d..0000000000 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/RuleSetTest.java +++ /dev/null @@ -1,468 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.mockito.Mockito.mock; - -import javax.security.auth.Subject; - -import org.apache.qpid.server.logging.EventLoggerProvider; -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.ObjectProperties.Property; -import org.apache.qpid.server.security.access.config.Rule; -import org.apache.qpid.server.security.access.config.RuleSet; -import org.apache.qpid.server.security.auth.TestPrincipalUtils; -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(Subject, Operation, ObjectType, ObjectProperties)} method. - * - * It ensure that permissions can be granted correctly on users directly and on groups. - */ -public class RuleSetTest extends QpidTestCase -{ - private static final String DENIED_VH = "deniedVH"; - private static final String ALLOWED_VH = "allowedVH"; - - private RuleSet _ruleSet; // Object under test - - private static final String TEST_USER = "user"; - - // Common things that are passed to frame constructors - private String _queueName = this.getClass().getName() + "queue"; - private String _exchangeName = "amq.direct"; - private String _exchangeType = "direct"; - private Subject _testSubject = TestPrincipalUtils.createTestSubject(TEST_USER); - - @Override - public void setUp() throws Exception - { - super.setUp(); - - _ruleSet = new RuleSet(mock(EventLoggerProvider.class)); - } - - @Override - public void tearDown() throws Exception - { - _ruleSet.clear(); - super.tearDown(); - } - - public void assertDenyGrantAllow(Subject subject, Operation operation, ObjectType objectType) - { - assertDenyGrantAllow(subject, operation, objectType, ObjectProperties.EMPTY); - } - - public void assertDenyGrantAllow(Subject subject, Operation operation, ObjectType objectType, ObjectProperties properties) - { - assertEquals(Result.DENIED, _ruleSet.check(subject, operation, objectType, properties)); - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, operation, objectType, properties); - assertEquals(1, _ruleSet.getRuleCount()); - assertEquals(Result.ALLOWED, _ruleSet.check(subject, operation, objectType, properties)); - } - - public void testEmptyRuleSet() - { - assertNotNull(_ruleSet); - assertEquals(_ruleSet.getRuleCount(), 0); - assertEquals(_ruleSet.getDefault(), _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - } - - public void testVirtualHostNodeCreateAllowPermissionWithVirtualHostName() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.VIRTUALHOSTNODE, ObjectProperties.EMPTY); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.VIRTUALHOSTNODE, ObjectProperties.EMPTY)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.DELETE, ObjectType.VIRTUALHOSTNODE, ObjectProperties.EMPTY)); - } - - public void testVirtualHostAccessAllowPermissionWithVirtualHostName() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); - assertEquals(Result.DEFER, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); - } - - public void testVirtualHostAccessAllowPermissionWithNameSetToWildCard() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ObjectProperties.WILD_CARD)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); - } - - public void testVirtualHostAccessAllowPermissionWithNoName() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); - } - - public void testVirtualHostAccessDenyPermissionWithNoName() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); - } - - public void testVirtualHostAccessDenyPermissionWithNameSetToWildCard() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ObjectProperties.WILD_CARD)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); - } - - public void testVirtualHostAccessAllowDenyPermissions() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH)); - _ruleSet.grant(1, TEST_USER, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(ALLOWED_VH))); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); - } - - public void testVirtualHostAccessAllowPermissionWithVirtualHostNameOtherPredicate() throws Exception - { - ObjectProperties properties = new ObjectProperties(); - properties.put(Property.VIRTUALHOST_NAME, ALLOWED_VH); - - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, properties); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, properties)); - assertEquals(Result.DEFER, _ruleSet.check(_testSubject, Operation.ACCESS, ObjectType.VIRTUALHOST, new ObjectProperties(DENIED_VH))); - } - - - public void testQueueCreateNamed() throws Exception - { - assertDenyGrantAllow(_testSubject, Operation.CREATE, ObjectType.QUEUE, new ObjectProperties(_queueName)); - } - - public void testQueueCreateNamedVirtualHost() throws Exception - { - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, new ObjectProperties(Property.VIRTUALHOST_NAME, ALLOWED_VH)); - - ObjectProperties allowedQueueObjectProperties = new ObjectProperties(_queueName); - allowedQueueObjectProperties.put(Property.VIRTUALHOST_NAME, ALLOWED_VH); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, new ObjectProperties(allowedQueueObjectProperties))); - - ObjectProperties deniedQueueObjectProperties = new ObjectProperties(_queueName); - deniedQueueObjectProperties.put(Property.VIRTUALHOST_NAME, DENIED_VH); - assertEquals(Result.DEFER, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, deniedQueueObjectProperties)); - } - - public void testQueueCreateNamedNullRoutingKey() - { - ObjectProperties properties = new ObjectProperties(_queueName); - properties.put(ObjectProperties.Property.ROUTING_KEY, (String) null); - - assertDenyGrantAllow(_testSubject, Operation.CREATE, ObjectType.QUEUE, properties); - } - - public void testExchangeCreateNamedVirtualHost() - { - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.EXCHANGE, new ObjectProperties(Property.VIRTUALHOST_NAME, ALLOWED_VH)); - - ObjectProperties allowedExchangeProperties = new ObjectProperties(_exchangeName); - allowedExchangeProperties.put(Property.TYPE, _exchangeType); - allowedExchangeProperties.put(Property.VIRTUALHOST_NAME, ALLOWED_VH); - - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.EXCHANGE, allowedExchangeProperties)); - - ObjectProperties deniedExchangeProperties = new ObjectProperties(_exchangeName); - deniedExchangeProperties.put(Property.TYPE, _exchangeType); - deniedExchangeProperties.put(Property.VIRTUALHOST_NAME, DENIED_VH); - assertEquals(Result.DEFER, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.EXCHANGE, deniedExchangeProperties)); - } - - public void testExchangeCreate() - { - ObjectProperties properties = new ObjectProperties(_exchangeName); - properties.put(ObjectProperties.Property.TYPE, _exchangeType); - - assertDenyGrantAllow(_testSubject, Operation.CREATE, ObjectType.EXCHANGE, properties); - } - - public void testConsume() - { - assertDenyGrantAllow(_testSubject, Operation.CONSUME, ObjectType.QUEUE); - } - - public void testPublish() - { - assertDenyGrantAllow(_testSubject, 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(_testSubject, Operation.CONSUME, ObjectType.QUEUE, temporary)); - _ruleSet.grant(0, TEST_USER, Permission.ALLOW, Operation.CONSUME, ObjectType.QUEUE, temporary); - assertEquals(1, _ruleSet.getRuleCount()); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, 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(_testSubject, 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(_testSubject, Operation.CONSUME, ObjectType.QUEUE, temporary)); - - // should not matter if the temporary permission is processed first or last - _ruleSet.grant(1, TEST_USER, Permission.ALLOW, Operation.CONSUME, ObjectType.QUEUE, normal); - _ruleSet.grant(2, TEST_USER, Permission.ALLOW, Operation.CONSUME, ObjectType.QUEUE, temporary); - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CONSUME, ObjectType.QUEUE, normal)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, 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(_testSubject, Operation.CONSUME, ObjectType.QUEUE, temporary)); - - // should not matter if the temporary permission is processed first or last - _ruleSet.grant(1, TEST_USER, Permission.ALLOW, Operation.CONSUME, ObjectType.QUEUE, temporary); - _ruleSet.grant(2, TEST_USER, Permission.ALLOW, Operation.CONSUME, ObjectType.QUEUE, normal); - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CONSUME, ObjectType.QUEUE, normal)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, 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(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - - _ruleSet.grant(1, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, named); - _ruleSet.grant(2, TEST_USER, Permission.DENY, Operation.CREATE, ObjectType.QUEUE, namedTemporary); - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, 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(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - - _ruleSet.grant(1, TEST_USER, Permission.DENY, Operation.CREATE, ObjectType.QUEUE, namedTemporary); - _ruleSet.grant(2, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, named); - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, 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(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedDurable)); - - _ruleSet.grant(1, TEST_USER, Permission.DENY, Operation.CREATE, ObjectType.QUEUE, namedTemporary); - _ruleSet.grant(2, TEST_USER, Permission.DENY, Operation.CREATE, ObjectType.QUEUE, namedDurable); - _ruleSet.grant(3, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, named); - assertEquals(3, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, 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(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - - _ruleSet.grant(1, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, namedTemporary); - _ruleSet.grant(2, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, named); - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, 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(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - - _ruleSet.grant(1, TEST_USER, Permission.ALLOW, Operation.CREATE, ObjectType.QUEUE, namedTemporary); - _ruleSet.grant(2, TEST_USER, Permission.DENY, Operation.CREATE, ObjectType.QUEUE, named); - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.DENIED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, named)); - assertEquals(Result.ALLOWED, _ruleSet.check(_testSubject, Operation.CREATE, ObjectType.QUEUE, namedTemporary)); - } - - /** - * Tests support for the {@link Rule#ALL} keyword. - */ - public void testAllowToAll() - { - _ruleSet.grant(1, Rule.ALL, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(1, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(TestPrincipalUtils.createTestSubject("usera"),Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - assertEquals(Result.ALLOWED, _ruleSet.check(TestPrincipalUtils.createTestSubject("userb"),Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - } - - public void testGroupsSupported() - { - String allowGroup = "allowGroup"; - String deniedGroup = "deniedGroup"; - - _ruleSet.grant(1, allowGroup, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - _ruleSet.grant(2, deniedGroup, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(TestPrincipalUtils.createTestSubject("usera", allowGroup),Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - assertEquals(Result.DENIED, _ruleSet.check(TestPrincipalUtils.createTestSubject("userb", deniedGroup),Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - assertEquals(Result.DEFER, _ruleSet.check(TestPrincipalUtils.createTestSubject("user", "group not mentioned in acl"),Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - } - - /** - * Rule order in the ACL determines the outcome of the check. This test ensures that a user who is - * granted explicit permission on an object, is granted that access even though a group - * to which the user belongs is later denied the permission. - */ - public void testAllowDeterminedByRuleOrder() - { - String group = "group"; - String user = "user"; - - _ruleSet.grant(1, user, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - _ruleSet.grant(2, group, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.ALLOWED, _ruleSet.check(TestPrincipalUtils.createTestSubject(user, group),Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - } - - /** - * Rule order in the ACL determines the outcome of the check. This tests ensures that a user who is denied - * access by group, is denied access, despite there being a later rule granting permission to that user. - */ - public void testDenyDeterminedByRuleOrder() - { - String group = "aclgroup"; - String user = "usera"; - - _ruleSet.grant(1, group, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - _ruleSet.grant(2, user, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - - assertEquals(2, _ruleSet.getRuleCount()); - - assertEquals(Result.DENIED, _ruleSet.check(TestPrincipalUtils.createTestSubject(user, group),Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - } - - public void testUserInMultipleGroups() - { - String allowedGroup = "group1"; - String deniedGroup = "group2"; - - _ruleSet.grant(1, allowedGroup, Permission.ALLOW, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - _ruleSet.grant(2, deniedGroup, Permission.DENY, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - - Subject subjectInBothGroups = TestPrincipalUtils.createTestSubject("user", allowedGroup, deniedGroup); - Subject subjectInDeniedGroupAndOneOther = TestPrincipalUtils.createTestSubject("user", deniedGroup, "some other group"); - Subject subjectInAllowedGroupAndOneOther = TestPrincipalUtils.createTestSubject("user", allowedGroup, "some other group"); - - assertEquals(Result.ALLOWED, _ruleSet.check(subjectInBothGroups,Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - - assertEquals(Result.DENIED, _ruleSet.check(subjectInDeniedGroupAndOneOther,Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - - assertEquals(Result.ALLOWED, _ruleSet.check(subjectInAllowedGroupAndOneOther,Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY)); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/pom.xml b/qpid/java/broker-plugins/amqp-0-10-protocol/pom.xml deleted file mode 100644 index 6006a2a723..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/pom.xml +++ /dev/null @@ -1,79 +0,0 @@ - - - - 4.0.0 - - - org.apache.qpid - qpid-java-build - 0.32-SNAPSHOT - ../../pom.xml - - - qpid-broker-plugins-amqp-0-10-protocol - Qpid AMQP 0-10 Protocol Plug-in - AMQP 0-10 protocol broker plug-in - - - - org.apache.qpid - qpid-broker-core - ${project.version} - provided - - - - org.apache.qpid - qpid-broker-codegen - ${project.version} - true - - - - log4j - log4j - ${log4j-version} - - - - org.slf4j - slf4j-api - ${slf4j-version} - - - - - org.apache.qpid - qpid-test-utils - ${project.version} - test - - - - org.apache.qpid - qpid-broker-core - ${project.version} - test-jar - test - - - - - - - diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ConsumerTarget_0_10.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ConsumerTarget_0_10.java deleted file mode 100644 index db053eef26..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ConsumerTarget_0_10.java +++ /dev/null @@ -1,669 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.v0_10; - -import java.nio.ByteBuffer; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; - -import org.apache.qpid.server.consumer.AbstractConsumerTarget; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.flow.FlowCreditManager; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.messages.ChannelMessages; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.model.Exchange; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.protocol.MessageConverterRegistry; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.QueueConsumer; -import org.apache.qpid.server.store.TransactionLogResource; -import org.apache.qpid.server.txn.AutoCommitTransaction; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -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.MessageFlowMode; -import org.apache.qpid.transport.MessageProperties; -import org.apache.qpid.transport.MessageTransfer; -import org.apache.qpid.transport.Method; -import org.apache.qpid.transport.Option; -import org.apache.qpid.util.GZIPUtils; - -public class ConsumerTarget_0_10 extends AbstractConsumerTarget implements FlowCreditManager.FlowCreditManagerListener -{ - - private static final Option[] BATCHED = new Option[] { Option.BATCH }; - - private final AtomicBoolean _deleted = new AtomicBoolean(false); - private final String _name; - - - private FlowCreditManager_0_10 _creditManager; - - private final MessageAcceptMode _acceptMode; - private final MessageAcquireMode _acquireMode; - private MessageFlowMode _flowMode; - private final ServerSession _session; - private final AtomicBoolean _stopped = new AtomicBoolean(true); - - private final AtomicLong _unacknowledgedCount = new AtomicLong(0); - private final AtomicLong _unacknowledgedBytes = new AtomicLong(0); - - private final Map _arguments; - private int _deferredMessageCredit; - private long _deferredSizeCredit; - private final List _consumers = new CopyOnWriteArrayList<>(); - - - public ConsumerTarget_0_10(ServerSession session, - String name, - MessageAcceptMode acceptMode, - MessageAcquireMode acquireMode, - MessageFlowMode flowMode, - FlowCreditManager_0_10 creditManager, - Map arguments) - { - super(State.SUSPENDED); - _session = session; - _postIdSettingAction = new AddMessageDispositionListenerAction(session); - _acceptMode = acceptMode; - _acquireMode = acquireMode; - _creditManager = creditManager; - _flowMode = flowMode; - _creditManager.addStateListener(this); - _arguments = arguments == null ? Collections. emptyMap() : - Collections. unmodifiableMap(arguments); - _name = name; - } - - @Override - public boolean doIsSuspended() - { - return getState()!=State.ACTIVE || _deleted.get() || _session.isClosing() || _session.getConnectionModel().isStopped(); // TODO check for Session suspension - } - - public boolean close() - { - boolean closed = false; - State state = getState(); - - getSendLock(); - try - { - while(!closed && state != State.CLOSED) - { - closed = updateState(state, State.CLOSED); - if(!closed) - { - state = getState(); - } - } - _creditManager.removeListener(this); - } - finally - { - releaseSendLock(); - } - - return closed; - - } - - public void creditStateChanged(boolean hasCredit) - { - - if(hasCredit) - { - if(!updateState(State.SUSPENDED, State.ACTIVE)) - { - // this is a hack to get round the issue of increasing bytes credit - notifyCurrentState(); - } - } - else - { - updateState(State.ACTIVE, State.SUSPENDED); - } - } - - public String getName() - { - return _name; - } - - public void transportStateChanged() - { - _creditManager.restoreCredit(0, 0); - } - - public static class AddMessageDispositionListenerAction implements Runnable - { - private MessageTransfer _xfr; - private ServerSession.MessageDispositionChangeListener _action; - private ServerSession _session; - - public AddMessageDispositionListenerAction(ServerSession session) - { - _session = session; - } - - public void setXfr(MessageTransfer xfr) - { - _xfr = xfr; - } - - public void setAction(ServerSession.MessageDispositionChangeListener action) - { - _action = action; - } - - public void run() - { - if(_action != null) - { - _session.onMessageDispositionChange(_xfr, _action); - } - } - } - - private final AddMessageDispositionListenerAction _postIdSettingAction; - - public void doSend(final ConsumerImpl consumer, final MessageInstance entry, boolean batch) - { - ServerMessage serverMsg = entry.getMessage(); - - - MessageTransfer xfr; - - DeliveryProperties deliveryProps; - MessageProperties messageProps = null; - - MessageTransferMessage msg; - - if(serverMsg instanceof MessageTransferMessage) - { - - msg = (MessageTransferMessage) serverMsg; - - } - else - { - MessageConverter converter = - MessageConverterRegistry.getConverter(serverMsg.getClass(), MessageTransferMessage.class); - - - msg = (MessageTransferMessage) converter.convert(serverMsg, _session.getVirtualHost()); - } - DeliveryProperties origDeliveryProps = msg.getHeader() == null ? null : msg.getHeader().getDeliveryProperties(); - messageProps = msg.getHeader() == null ? null : msg.getHeader().getMessageProperties(); - - 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()); - } - if(origDeliveryProps.hasTtl()) - { - deliveryProps.setTtl(origDeliveryProps.getTtl()); - } - - - } - - deliveryProps.setRedelivered(entry.isRedelivered()); - - boolean msgCompressed = messageProps != null && GZIPUtils.GZIP_CONTENT_ENCODING.equals(messageProps.getContentEncoding()); - - - ByteBuffer body = msg.getBody(); - - boolean compressionSupported = _session.getConnection().getConnectionDelegate().isCompressionSupported(); - - if(msgCompressed && !compressionSupported) - { - byte[] uncompressed = GZIPUtils.uncompressBufferToArray(body); - if(uncompressed != null) - { - messageProps.setContentEncoding(null); - body = ByteBuffer.wrap(uncompressed); - } - } - else if(!msgCompressed - && compressionSupported - && (messageProps == null || messageProps.getContentEncoding()==null) - && body != null - && body.remaining() > _session.getConnection().getMessageCompressionThreshold()) - { - byte[] compressed = GZIPUtils.compressBufferToArray(body); - if(compressed != null) - { - if(messageProps == null) - { - messageProps = new MessageProperties(); - } - messageProps.setContentEncoding(GZIPUtils.GZIP_CONTENT_ENCODING); - body = ByteBuffer.wrap(compressed); - } - } - long size = body == null ? 0 : body.remaining(); - - Header header = new Header(deliveryProps, messageProps, msg.getHeader() == null ? null : msg.getHeader().getNonStandardProperties()); - - xfr = batch ? new MessageTransfer(_name,_acceptMode,_acquireMode,header, body, BATCHED) - : new MessageTransfer(_name,_acceptMode,_acquireMode,header, body); - - if(_acceptMode == MessageAcceptMode.NONE && _acquireMode != MessageAcquireMode.PRE_ACQUIRED) - { - xfr.setCompletionListener(new MessageAcceptCompletionListener(this, consumer, _session, entry, _flowMode == MessageFlowMode.WINDOW)); - } - else if(_flowMode == MessageFlowMode.WINDOW) - { - xfr.setCompletionListener(new Method.CompletionListener() - { - public void onComplete(Method method) - { - deferredAddCredit(1, entry.getMessage().getSize()); - } - }); - } - - - _postIdSettingAction.setXfr(xfr); - if(_acceptMode == MessageAcceptMode.EXPLICIT) - { - _postIdSettingAction.setAction(new ExplicitAcceptDispositionChangeListener(entry, this, consumer)); - } - else if(_acquireMode != MessageAcquireMode.PRE_ACQUIRED) - { - _postIdSettingAction.setAction(new ImplicitAcceptDispositionChangeListener(entry, this, consumer)); - } - else - { - _postIdSettingAction.setAction(null); - } - - - _session.sendMessage(xfr, _postIdSettingAction); - - _postIdSettingAction.setAction(null); - _postIdSettingAction.setXfr(null); - - entry.incrementDeliveryCount(); - if(_acceptMode == MessageAcceptMode.NONE && _acquireMode == MessageAcquireMode.PRE_ACQUIRED) - { - forceDequeue(entry, false); - } - else if(_acquireMode == MessageAcquireMode.PRE_ACQUIRED) - { - recordUnacknowledged(entry); - } - } - - void recordUnacknowledged(MessageInstance entry) - { - _unacknowledgedCount.incrementAndGet(); - _unacknowledgedBytes.addAndGet(entry.getMessage().getSize()); - } - - private void deferredAddCredit(final int deferredMessageCredit, final long deferredSizeCredit) - { - _deferredMessageCredit += deferredMessageCredit; - _deferredSizeCredit += deferredSizeCredit; - - } - - public void flushCreditState(boolean strict) - { - if(strict || !isSuspended() || _deferredMessageCredit >= 200 - || !(_creditManager instanceof WindowCreditManager) - || ((WindowCreditManager)_creditManager).getMessageCreditLimit() < 400 ) - { - _creditManager.restoreCredit(_deferredMessageCredit, _deferredSizeCredit); - _deferredMessageCredit = 0; - _deferredSizeCredit = 0l; - } - } - - private void forceDequeue(final MessageInstance entry, final boolean restoreCredit) - { - AutoCommitTransaction dequeueTxn = new AutoCommitTransaction(_session.getVirtualHost().getMessageStore()); - dequeueTxn.dequeue(entry.getEnqueueRecord(), - new ServerTransaction.Action() - { - public void postCommit() - { - if (restoreCredit) - { - restoreCredit(entry.getMessage()); - } - entry.delete(); - } - - public void onRollback() - { - - } - }); - } - - void reject(final MessageInstance entry) - { - entry.setRedelivered(); - entry.routeToAlternate(null, null); - if(isAcquiredByConsumer(entry)) - { - entry.delete(); - } - } - - private boolean isAcquiredByConsumer(final MessageInstance entry) - { - ConsumerImpl acquiringConsumer = entry.getAcquiringConsumer(); - if(acquiringConsumer instanceof QueueConsumer) - { - return ((QueueConsumer)acquiringConsumer).getTarget() == this; - } - - return false; - } - - void release(final MessageInstance entry, final boolean setRedelivered) - { - if (setRedelivered) - { - entry.setRedelivered(); - } - - if (getSessionModel().isClosing() || !setRedelivered) - { - entry.decrementDeliveryCount(); - } - - if (isMaxDeliveryLimitReached(entry)) - { - sendToDLQOrDiscard(entry); - } - else - { - entry.release(); - } - } - - protected void sendToDLQOrDiscard(MessageInstance entry) - { - final ServerMessage msg = entry.getMessage(); - - int requeues = entry.routeToAlternate(new Action() - { - @Override - public void performAction(final MessageInstance requeueEntry) - { - getEventLogger().message(ChannelMessages.DEADLETTERMSG(msg.getMessageNumber(), - requeueEntry.getOwningResource() - .getName())); - } - }, null); - - if (requeues == 0) - { - TransactionLogResource owningResource = entry.getOwningResource(); - if(owningResource instanceof AMQQueue) - { - final AMQQueue queue = (AMQQueue)owningResource; - final Exchange alternateExchange = queue.getAlternateExchange(); - - if(alternateExchange != null) - { - getEventLogger().message(ChannelMessages.DISCARDMSG_NOROUTE(msg.getMessageNumber(), - alternateExchange.getName())); - } - else - { - getEventLogger().message(ChannelMessages.DISCARDMSG_NOALTEXCH(msg.getMessageNumber(), - queue.getName(), - msg.getInitialRoutingAddress())); - } - } - } - } - - protected EventLogger getEventLogger() - { - return getSessionModel().getVirtualHost().getEventLogger(); - } - - private boolean isMaxDeliveryLimitReached(MessageInstance entry) - { - final int maxDeliveryLimit = entry.getMaximumDeliveryCount(); - return (maxDeliveryLimit > 0 && entry.getDeliveryCount() >= maxDeliveryLimit); - } - - public void queueDeleted() - { - _deleted.set(true); - } - - public boolean allocateCredit(ServerMessage message) - { - return _creditManager.useCreditForMessage(message.getSize()); - } - - public void restoreCredit(ServerMessage message) - { - _creditManager.restoreCredit(1, message.getSize()); - } - - public FlowCreditManager_0_10 getCreditManager() - { - return _creditManager; - } - - - public void stop() - { - try - { - getSendLock(); - - updateState(State.ACTIVE, State.SUSPENDED); - _stopped.set(true); - FlowCreditManager_0_10 creditManager = getCreditManager(); - creditManager.clearCredit(); - } - finally - { - releaseSendLock(); - } - } - - 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()) - { - updateState(State.SUSPENDED, State.ACTIVE); - } - - } - - public void setFlowMode(MessageFlowMode flowMode) - { - - - _creditManager.removeListener(this); - - switch(flowMode) - { - case CREDIT: - _creditManager = new CreditCreditManager(0l, 0l, _session.getConnection().getProtocolEngine()); - break; - case WINDOW: - _creditManager = new WindowCreditManager(0l, 0l, _session.getConnection().getProtocolEngine()); - break; - default: - // this should never happen, as 0-10 is finalised and so the enum should never change - throw new ConnectionScopedRuntimeException("Unknown message flow mode: " + flowMode); - } - _flowMode = flowMode; - updateState(State.ACTIVE, State.SUSPENDED); - - _creditManager.addStateListener(this); - - } - - public boolean isStopped() - { - return _stopped.get(); - } - - public boolean deleteAcquired(MessageInstance entry) - { - if(isAcquiredByConsumer(entry)) - { - acquisitionRemoved(entry); - entry.delete(); - return true; - } - else - { - return false; - } - } - - @Override - public void acquisitionRemoved(final MessageInstance entry) - { - _unacknowledgedBytes.addAndGet(-entry.getMessage().getSize()); - _unacknowledgedCount.decrementAndGet(); - } - - public void flush() - { - flushCreditState(true); - for(ConsumerImpl consumer : _consumers) - { - consumer.flush(); - } - stop(); - } - - public ServerSession getSessionModel() - { - return _session; - } - - public boolean isDurable() - { - return false; - } - - public Map getArguments() - { - return _arguments; - } - - public void queueEmpty() - { - } - - public void flushBatched() - { - } - - - @Override - public void consumerAdded(final ConsumerImpl sub) - { - _consumers.add(sub); - } - - @Override - public void consumerRemoved(final ConsumerImpl sub) - { - _consumers.remove(sub); - if(_consumers.isEmpty()) - { - close(); - } - } - - public long getUnacknowledgedBytes() - { - return _unacknowledgedBytes.longValue(); - } - - public long getUnacknowledgedMessages() - { - return _unacknowledgedCount.longValue(); - } - - @Override - protected void processClosed() - { - - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/CreditCreditManager.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/CreditCreditManager.java deleted file mode 100644 index dd43ae7e11..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/CreditCreditManager.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.protocol.v0_10; - - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.flow.AbstractFlowCreditManager; - -public class CreditCreditManager extends AbstractFlowCreditManager implements FlowCreditManager_0_10 -{ - private final ServerProtocolEngine _serverProtocolEngine; - private volatile long _bytesCredit; - private volatile long _messageCredit; - - public CreditCreditManager(long bytesCredit, long messageCredit, final ServerProtocolEngine serverProtocolEngine) - { - _serverProtocolEngine = serverProtocolEngine; - _bytesCredit = bytesCredit; - _messageCredit = messageCredit; - setSuspended(!hasCredit()); - - } - - public synchronized void restoreCredit(final long messageCredit, final long bytesCredit) - { - setSuspended(!hasCredit()); - } - - - 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 && !_serverProtocolEngine.isTransportBlockedForWriting()); - } - - public synchronized boolean useCreditForMessage(long msgSize) - { - if (_serverProtocolEngine.isTransportBlockedForWriting()) - { - setSuspended(true); - return false; - } - else if(_messageCredit >= 0L) - { - if(_messageCredit > 0) - { - if(_bytesCredit < 0L) - { - _messageCredit--; - - return true; - } - else if(msgSize <= _bytesCredit) - { - _messageCredit--; - _bytesCredit -= msgSize; - - return true; - } - else - { - return false; - } - } - else - { - setSuspended(true); - return false; - } - } - else if(_bytesCredit >= 0L) - { - if(msgSize <= _bytesCredit) - { - _bytesCredit -= msgSize; - - return true; - } - else - { - return false; - } - - } - else - { - return true; - } - - } - - public synchronized void stop() - { - if(_bytesCredit > 0) - { - _bytesCredit = 0; - } - if(_messageCredit > 0) - { - _messageCredit = 0; - } - - } - - -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ExplicitAcceptDispositionChangeListener.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ExplicitAcceptDispositionChangeListener.java deleted file mode 100755 index 2118a00477..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ExplicitAcceptDispositionChangeListener.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.protocol.v0_10; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.MessageInstance; - - -class ExplicitAcceptDispositionChangeListener implements ServerSession.MessageDispositionChangeListener -{ - private static final Logger _logger = LoggerFactory.getLogger(ExplicitAcceptDispositionChangeListener.class); - - - private final MessageInstance _entry; - private final ConsumerTarget_0_10 _target; - private final ConsumerImpl _consumer; - - public ExplicitAcceptDispositionChangeListener(MessageInstance entry, - ConsumerTarget_0_10 target, - final ConsumerImpl consumer) - { - _entry = entry; - _target = target; - _consumer = consumer; - } - - public void onAccept() - { - if(_target != null && _entry.isAcquiredBy(_consumer) && _entry.lockAcquisition()) - { - _target.getSessionModel().acknowledge(_target, _entry); - } - else - { - _logger.debug("MessageAccept received for message which is not been acquired - message may have expired or been removed"); - } - - } - - public void onRelease(boolean setRedelivered) - { - if(_target != null && _entry.isAcquiredBy(_consumer)) - { - _target.release(_entry, setRedelivered); - } - else - { - _logger.debug("MessageRelease received for message which has not been acquired - message may have expired or been removed"); - } - } - - public void onReject() - { - if(_target != null && _entry.isAcquiredBy(_consumer)) - { - _target.reject(_entry); - } - else - { - _logger.debug("MessageReject received for message which has not been acquired - message may have expired or been removed"); - } - - } - - public boolean acquire() - { - return _entry.acquire(_consumer); - } - - -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/FlowCreditManager_0_10.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/FlowCreditManager_0_10.java deleted file mode 100755 index 7f092814da..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/FlowCreditManager_0_10.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.protocol.v0_10; - -import org.apache.qpid.server.flow.FlowCreditManager; - -public interface FlowCreditManager_0_10 extends FlowCreditManager -{ - public void addCredit(long count, long bytes); - - void clearCredit(); -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ImplicitAcceptDispositionChangeListener.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ImplicitAcceptDispositionChangeListener.java deleted file mode 100755 index c918016fb1..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ImplicitAcceptDispositionChangeListener.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.protocol.v0_10; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.MessageInstance; - -class ImplicitAcceptDispositionChangeListener implements ServerSession.MessageDispositionChangeListener -{ - private static final Logger _logger = LoggerFactory.getLogger(ImplicitAcceptDispositionChangeListener.class); - - - private final MessageInstance _entry; - private final ConsumerTarget_0_10 _target; - private final ConsumerImpl _consumer; - - public ImplicitAcceptDispositionChangeListener(MessageInstance entry, - ConsumerTarget_0_10 target, - final ConsumerImpl consumer) - { - _entry = entry; - _target = target; - _consumer = consumer; - } - - public void onAccept() - { - _logger.warn("MessageAccept received for message which is using NONE as the accept mode (likely client error)"); - } - - public void onRelease(boolean setRedelivered) - { - if(_entry.isAcquiredBy(_consumer)) - { - _target.release(_entry, setRedelivered); - } - else - { - _logger.warn("MessageRelease received for message which has not been acquired (likely client error)"); - } - } - - public void onReject() - { - if(_entry.isAcquiredBy(_consumer)) - { - _target.reject(_entry); - } - else - { - _logger.warn("MessageReject received for message which has not been acquired (likely client error)"); - } - - } - - public boolean acquire() - { - boolean acquired = _entry.acquire(_consumer); - if(acquired) - { - _target.recordUnacknowledged(_entry); - } - return acquired; - - } - - - -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageAcceptCompletionListener.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageAcceptCompletionListener.java deleted file mode 100755 index d581d146a8..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageAcceptCompletionListener.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.v0_10; - -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.transport.Method; - -public class MessageAcceptCompletionListener implements Method.CompletionListener -{ - private final ConsumerTarget_0_10 _sub; - private final MessageInstance _entry; - private final ServerSession _session; - private final ConsumerImpl _consumer; - private long _messageSize; - private boolean _restoreCredit; - - public MessageAcceptCompletionListener(ConsumerTarget_0_10 sub, - final ConsumerImpl consumer, - ServerSession session, - MessageInstance entry, - boolean restoreCredit) - { - super(); - _sub = sub; - _entry = entry; - _session = session; - _restoreCredit = restoreCredit; - _consumer = consumer; - if(restoreCredit) - { - _messageSize = entry.getMessage().getSize(); - } - } - - public void onComplete(Method method) - { - if(_restoreCredit) - { - _sub.getCreditManager().restoreCredit(1l, _messageSize); - } - if(_entry.isAcquiredBy(_consumer) && _entry.lockAcquisition()) - { - _session.acknowledge(_sub, _entry); - } - - _session.removeDispositionListener(method); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_Internal_to_v0_10.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_Internal_to_v0_10.java deleted file mode 100644 index bd04db11ae..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_Internal_to_v0_10.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.v0_10; - -import java.nio.ByteBuffer; - -import org.apache.qpid.server.message.internal.InternalMessage; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.Header; -import org.apache.qpid.transport.MessageDeliveryPriority; -import org.apache.qpid.transport.MessageProperties; - -@PluggableService -public class MessageConverter_Internal_to_v0_10 implements MessageConverter -{ - @Override - public Class getInputClass() - { - return InternalMessage.class; - } - - @Override - public Class getOutputClass() - { - return MessageTransferMessage.class; - } - - @Override - public MessageTransferMessage convert(InternalMessage serverMsg, VirtualHostImpl vhost) - { - return new MessageTransferMessage(convertToStoredMessage(serverMsg), null); - } - - private StoredMessage convertToStoredMessage(final InternalMessage serverMsg) - { - final byte[] messageContent = MessageConverter_v0_10.convertToBody(serverMsg.getMessageBody()); - final MessageMetaData_0_10 messageMetaData_0_10 = convertMetaData(serverMsg, - MessageConverter_v0_10.getBodyMimeType( - serverMsg.getMessageBody()), - messageContent.length); - - return new StoredMessage() - { - @Override - public MessageMetaData_0_10 getMetaData() - { - return messageMetaData_0_10; - } - - @Override - public long getMessageNumber() - { - return serverMsg.getMessageNumber(); - } - - @Override - public int getContent(int offsetInMessage, ByteBuffer dst) - { - int size = messageContent.length - offsetInMessage; - if(dst.remaining() < size) - { - size = dst.remaining(); - } - ByteBuffer buf = ByteBuffer.wrap(messageContent, offsetInMessage, size); - dst.put(buf); - return size; - } - - @Override - public ByteBuffer getContent(int offsetInMessage, int size) - { - return ByteBuffer.wrap(messageContent, offsetInMessage, size); - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isInMemory() - { - return true; - } - - @Override - public boolean flowToDisk() - { - return false; - } - }; - } - - private MessageMetaData_0_10 convertMetaData(InternalMessage serverMsg, final String bodyMimeType, final int size) - { - DeliveryProperties deliveryProps = new DeliveryProperties(); - MessageProperties messageProps = new MessageProperties(); - - - - deliveryProps.setExpiration(serverMsg.getExpiration()); - deliveryProps.setPriority(MessageDeliveryPriority.get(serverMsg.getMessageHeader().getPriority())); - deliveryProps.setRoutingKey(serverMsg.getInitialRoutingAddress()); - deliveryProps.setTimestamp(serverMsg.getMessageHeader().getTimestamp()); - - messageProps.setContentEncoding(serverMsg.getMessageHeader().getEncoding()); - messageProps.setContentLength(size); - messageProps.setContentType(bodyMimeType); - if(serverMsg.getMessageHeader().getCorrelationId() != null) - { - messageProps.setCorrelationId(serverMsg.getMessageHeader().getCorrelationId().getBytes()); - } - messageProps.setApplicationHeaders(serverMsg.getMessageHeader().getHeaderMap()); - Header header = new Header(deliveryProps, messageProps, null); - return new MessageMetaData_0_10(header, size, serverMsg.getArrivalTime()); - } - - - @Override - public String getType() - { - return "Internal to v0-10"; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10.java deleted file mode 100644 index bd99458d51..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10.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.server.protocol.v0_10; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.util.List; -import java.util.Map; - -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.Header; -import org.apache.qpid.transport.MessageDeliveryPriority; -import org.apache.qpid.transport.MessageProperties; -import org.apache.qpid.transport.codec.BBEncoder; - -@PluggableService -public class MessageConverter_v0_10 implements MessageConverter -{ - - public static final Charset UTF_8 = Charset.forName("UTF-8"); - - @Override - public Class getInputClass() - { - return ServerMessage.class; - } - - @Override - public Class getOutputClass() - { - return MessageTransferMessage.class; - } - - @Override - public MessageTransferMessage convert(ServerMessage serverMsg, VirtualHostImpl vhost) - { - return new MessageTransferMessage(convertToStoredMessage(serverMsg), null); - } - - private StoredMessage convertToStoredMessage(final ServerMessage serverMsg) - { - final MessageMetaData_0_10 messageMetaData_0_10 = convertMetaData(serverMsg); - - return new StoredMessage() - { - @Override - public MessageMetaData_0_10 getMetaData() - { - return messageMetaData_0_10; - } - - @Override - public long getMessageNumber() - { - return serverMsg.getMessageNumber(); - } - - @Override - public int getContent(int offsetInMessage, ByteBuffer dst) - { - return serverMsg.getContent(dst, offsetInMessage); - } - - @Override - public ByteBuffer getContent(int offsetInMessage, int size) - { - return serverMsg.getContent(offsetInMessage, size); - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isInMemory() - { - return true; - } - - @Override - public boolean flowToDisk() - { - return false; - } - }; - } - - private MessageMetaData_0_10 convertMetaData(ServerMessage serverMsg) - { - DeliveryProperties deliveryProps = new DeliveryProperties(); - MessageProperties messageProps = new MessageProperties(); - - int size = (int) serverMsg.getSize(); - ByteBuffer body = ByteBuffer.allocate(size); - serverMsg.getContent(body, 0); - body.flip(); - - - deliveryProps.setExpiration(serverMsg.getExpiration()); - deliveryProps.setPriority(MessageDeliveryPriority.get(serverMsg.getMessageHeader().getPriority())); - deliveryProps.setRoutingKey(serverMsg.getInitialRoutingAddress()); - 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()); - } - - Header header = new Header(deliveryProps, messageProps, null); - return new MessageMetaData_0_10(header, size, serverMsg.getArrivalTime()); - } - - - public static byte[] convertToBody(Object object) - { - if(object instanceof String) - { - return ((String)object).getBytes(UTF_8); - } - else if(object instanceof byte[]) - { - return (byte[]) object; - } - else if(object instanceof Map) - { - BBEncoder encoder = new BBEncoder(1024); - encoder.writeMap((Map)object); - ByteBuffer buf = encoder.segment(); - int remaining = buf.remaining(); - byte[] data = new byte[remaining]; - buf.get(data); - return data; - - } - else if(object instanceof List) - { - BBEncoder encoder = new BBEncoder(1024); - encoder.writeList((List) object); - ByteBuffer buf = encoder.segment(); - int remaining = buf.remaining(); - byte[] data = new byte[remaining]; - buf.get(data); - return data; - } - else - { - ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); - try - { - ObjectOutputStream os = new ObjectOutputStream(bytesOut); - os.writeObject(object); - return bytesOut.toByteArray(); - } - catch (IOException e) - { - throw new ConnectionScopedRuntimeException(e); - } - } - } - - public static String getBodyMimeType(Object object) - { - if(object instanceof String) - { - return "text/plain"; - } - else if(object instanceof byte[]) - { - return "application/octet-stream"; - } - else if(object instanceof Map) - { - return "amqp/map"; - } - else if(object instanceof List) - { - return "amqp/list"; - } - else - { - return "application/java-object-stream"; - } - } - - - @Override - public String getType() - { - return "Unknown to v0-10"; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10_to_Internal.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10_to_Internal.java deleted file mode 100644 index 52bef63f7b..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10_to_Internal.java +++ /dev/null @@ -1,266 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.v0_10; - -import java.io.EOFException; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.internal.InternalMessage; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.MessageProperties; -import org.apache.qpid.transport.ReplyTo; -import org.apache.qpid.transport.codec.BBDecoder; -import org.apache.qpid.typedmessage.TypedBytesContentReader; -import org.apache.qpid.typedmessage.TypedBytesFormatException; - -@PluggableService -public class MessageConverter_v0_10_to_Internal implements MessageConverter -{ - @Override - public Class getInputClass() - { - return MessageTransferMessage.class; - } - - @Override - public Class getOutputClass() - { - return InternalMessage.class; - } - - @Override - public InternalMessage convert(MessageTransferMessage serverMessage, VirtualHostImpl vhost) - { - final String mimeType = serverMessage.getMessageHeader().getMimeType(); - byte[] data = new byte[(int) serverMessage.getSize()]; - serverMessage.getContent(ByteBuffer.wrap(data), 0); - - Object body = convertMessageBody(mimeType, data); - MessageProperties messageProps = serverMessage.getHeader().getMessageProperties(); - AMQMessageHeader fixedHeader = new DelegatingMessageHeader(serverMessage.getMessageHeader(), messageProps == null ? null : messageProps.getReplyTo()); - return InternalMessage.convert(serverMessage.getMessageNumber(), serverMessage.isPersistent(), fixedHeader, body); - } - - private static class DelegatingMessageHeader implements AMQMessageHeader - { - private final AMQMessageHeader _delegate; - private final ReplyTo _replyTo; - - - private DelegatingMessageHeader(final AMQMessageHeader delegate, final ReplyTo replyTo) - { - _delegate = delegate; - _replyTo = replyTo; - } - - @Override - public String getCorrelationId() - { - return _delegate.getCorrelationId(); - } - - @Override - public long getExpiration() - { - return _delegate.getExpiration(); - } - - @Override - public String getUserId() - { - return _delegate.getUserId(); - } - - @Override - public String getAppId() - { - return _delegate.getAppId(); - } - - @Override - public String getMessageId() - { - return _delegate.getMessageId(); - } - - @Override - public String getMimeType() - { - return _delegate.getMimeType(); - } - - @Override - public String getEncoding() - { - return _delegate.getEncoding(); - } - - @Override - public byte getPriority() - { - return _delegate.getPriority(); - } - - @Override - public long getTimestamp() - { - return _delegate.getTimestamp(); - } - - @Override - public String getType() - { - return _delegate.getType(); - } - - @Override - public String getReplyTo() - { - return _replyTo == null - ? null - : _replyTo.getExchange() == null || _replyTo.getExchange().equals("") - ? _replyTo.getRoutingKey() - : _replyTo.getRoutingKey() == null || _replyTo.getRoutingKey().equals("") - ? _replyTo.getExchange() - : _replyTo.getExchange() + "/" + _replyTo.getRoutingKey(); - } - - @Override - public Object getHeader(final String name) - { - return _delegate.getHeader(name); - } - - @Override - public boolean containsHeaders(final Set names) - { - return _delegate.containsHeaders(names); - } - - @Override - public boolean containsHeader(final String name) - { - return _delegate.containsHeader(name); - } - - @Override - public Collection getHeaderNames() - { - return _delegate.getHeaderNames(); - } - } - - private static Object convertMessageBody(String mimeType, byte[] data) - { - if("text/plain".equals(mimeType) || "text/xml".equals(mimeType)) - { - String text = new String(data); - return text; - } - else if("jms/map-message".equals(mimeType)) - { - TypedBytesContentReader reader = new TypedBytesContentReader(ByteBuffer.wrap(data)); - - LinkedHashMap map = new LinkedHashMap(); - final int entries = reader.readIntImpl(); - for (int i = 0; i < entries; i++) - { - try - { - String propName = reader.readStringImpl(); - Object value = reader.readObject(); - - map.put(propName, value); - } - catch (EOFException e) - { - throw new IllegalArgumentException(e); - } - catch (TypedBytesFormatException e) - { - throw new IllegalArgumentException(e); - } - - } - - return map; - - } - else if("amqp/map".equals(mimeType)) - { - BBDecoder decoder = new BBDecoder(); - decoder.init(ByteBuffer.wrap(data)); - final Map map = decoder.readMap(); - - return map; - - } - else if("amqp/list".equals(mimeType)) - { - BBDecoder decoder = new BBDecoder(); - decoder.init(ByteBuffer.wrap(data)); - return decoder.readList(); - } - else if("jms/stream-message".equals(mimeType)) - { - TypedBytesContentReader reader = new TypedBytesContentReader(ByteBuffer.wrap(data)); - - List list = new ArrayList(); - while (reader.remaining() != 0) - { - try - { - list.add(reader.readObject()); - } - catch (TypedBytesFormatException e) - { - throw new ConnectionScopedRuntimeException(e); - } - catch (EOFException e) - { - throw new ConnectionScopedRuntimeException(e); // TODO - Implement - } - } - return list; - } - else - { - return data; - - } - } - - @Override - public String getType() - { - return "v0-10 to Internal"; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaDataType_0_10.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaDataType_0_10.java deleted file mode 100644 index bac7e2d01f..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaDataType_0_10.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.protocol.v0_10; - -import java.nio.ByteBuffer; - -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.plugin.MessageMetaDataType; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.store.StoredMessage; - -@PluggableService -public class MessageMetaDataType_0_10 implements MessageMetaDataType -{ - - public static final int TYPE = 1; - public static final String V0_10 = "v0_10"; - - @Override - public int ordinal() - { - return TYPE; - } - - @Override - public MessageMetaData_0_10 createMetaData(ByteBuffer buf) - { - return MessageMetaData_0_10.FACTORY.createMetaData(buf); - } - - @Override - public ServerMessage createMessage(StoredMessage msg) - { - return new MessageTransferMessage(msg, null); - } - - public int hashCode() - { - return ordinal(); - } - - public boolean equals(Object o) - { - return o != null && o.getClass() == getClass(); - } - - @Override - public String getType() - { - return V0_10; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaData_0_10.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaData_0_10.java deleted file mode 100755 index 687331e51d..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaData_0_10.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.protocol.v0_10; - -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.plugin.MessageMetaDataType; -import org.apache.qpid.server.store.StorableMessageMetaData; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.Header; -import org.apache.qpid.transport.MessageDeliveryMode; -import org.apache.qpid.transport.MessageProperties; -import org.apache.qpid.transport.MessageTransfer; -import org.apache.qpid.transport.Struct; -import org.apache.qpid.transport.codec.BBDecoder; -import org.apache.qpid.transport.codec.BBEncoder; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.List; - -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 static final int ENCODER_SIZE = 1 << 10; - - public static final MessageMetaDataType.Factory FACTORY = new MetaDataFactory(); - - private static final MessageMetaDataType_0_10 TYPE = new MessageMetaDataType_0_10(); - - private volatile ByteBuffer _encoded; - - public MessageMetaData_0_10(MessageTransfer xfr) - { - this(xfr.getHeader(), xfr.getBodySize(), System.currentTimeMillis()); - } - - public MessageMetaData_0_10(Header header, int bodySize, long arrivalTime) - { - _header = header; - if(_header != null) - { - _deliveryProps = _header.getDeliveryProperties(); - _messageProps = _header.getMessageProperties(); - } - else - { - _deliveryProps = null; - _messageProps = null; - } - _messageHeader = new MessageTransferHeader(_deliveryProps, _messageProps); - _arrivalTime = arrivalTime; - _bodySize = bodySize; - - } - - - - public MessageMetaDataType getType() - { - return TYPE; - } - - 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); - int headersLength = 0; - if(_header.getDeliveryProperties() != null) - { - headersLength++; - } - if(_header.getMessageProperties() != null) - { - headersLength++; - } - if(_header.getNonStandardProperties() != null) - { - headersLength += _header.getNonStandardProperties().size(); - } - - encoder.writeInt32(headersLength); - - if(_header.getDeliveryProperties() != null) - { - encoder.writeStruct32(_header.getDeliveryProperties()); - } - if(_header.getMessageProperties() != null) - { - encoder.writeStruct32(_header.getMessageProperties()); - } - if(_header.getNonStandardProperties() != null) - { - - for(Struct header : _header.getNonStandardProperties()) - { - encoder.writeStruct32(header); - } - - } - ByteBuffer buf = encoder.buffer(); - return buf; - } - - public int writeToBuffer(ByteBuffer dest) - { - ByteBuffer buf = _encoded; - - if(buf == null) - { - buf = encodeAsBuffer(); - _encoded = buf; - } - - buf = buf.duplicate(); - - buf.position(0); - - 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; - } - - private static class MetaDataFactory implements MessageMetaDataType.Factory - { - 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(); - - DeliveryProperties deliveryProperties = null; - MessageProperties messageProperties = null; - List otherProps = null; - - for(int i = 0 ; i < headerCount; i++) - { - Struct struct = decoder.readStruct32(); - if(struct instanceof DeliveryProperties && deliveryProperties == null) - { - deliveryProperties = (DeliveryProperties) struct; - } - else if(struct instanceof MessageProperties && messageProperties == null) - { - messageProperties = (MessageProperties) struct; - } - else - { - if(otherProps == null) - { - otherProps = new ArrayList(); - - } - otherProps.add(struct); - } - } - Header header = new Header(deliveryProperties,messageProperties,otherProps); - - return new MessageMetaData_0_10(header, bodySize, arrivalTime); - - } - } - - -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageTransferHeader.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageTransferHeader.java deleted file mode 100644 index 1b506d9bf8..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageTransferHeader.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.server.protocol.v0_10; - -import java.util.*; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.MessageDeliveryPriority; -import org.apache.qpid.transport.MessageProperties; - -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 getUserId() - { - byte[] userIdBytes = _messageProps == null ? null : _messageProps.getUserId(); - return userIdBytes == null ? null : new String(userIdBytes); - } - - public String getAppId() - { - byte[] appIdBytes = _messageProps == null ? null : _messageProps.getAppId(); - return appIdBytes == null ? null : new String(appIdBytes); - } - - 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 || !_deliveryProps.hasPriority() - ? 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 appHeaders = _messageProps == null ? null : _messageProps.getApplicationHeaders(); - return appHeaders == null ? null : appHeaders.get(name); - } - - public boolean containsHeaders(Set names) - { - Map appHeaders = _messageProps == null ? null : _messageProps.getApplicationHeaders(); - return appHeaders != null && appHeaders.keySet().containsAll(names); - - } - - @Override - public Collection getHeaderNames() - { - Map appHeaders = _messageProps == null ? null : _messageProps.getApplicationHeaders(); - return appHeaders != null ? Collections.unmodifiableCollection(appHeaders.keySet()) : Collections.EMPTY_SET ; - - } - - public boolean containsHeader(String name) - { - Map appHeaders = _messageProps == null ? null : _messageProps.getApplicationHeaders(); - return appHeaders != null && appHeaders.containsKey(name); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageTransferMessage.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageTransferMessage.java deleted file mode 100644 index cca376c54c..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageTransferMessage.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.protocol.v0_10; - -import java.nio.ByteBuffer; - -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.AbstractServerMessageImpl; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.transport.Header; - - -public class MessageTransferMessage extends AbstractServerMessageImpl -{ - - public MessageTransferMessage(StoredMessage storeMessage, Object connectionRef) - { - super(storeMessage, connectionRef); - } - - private MessageMetaData_0_10 getMetaData() - { - return getStoredMessage().getMetaData(); - } - - public String getInitialRoutingAddress() - { - return getMetaData().getRoutingKey(); - } - - public AMQMessageHeader getMessageHeader() - { - return getMetaData().getMessageHeader(); - } - - public long getSize() - { - return getMetaData().getSize(); - } - - public boolean isImmediate() - { - return getMetaData().isImmediate(); - } - - public long getExpiration() - { - return getMetaData().getExpiration(); - } - - public long getArrivalTime() - { - return getMetaData().getArrivalTime(); - } - - public Header getHeader() - { - return getMetaData().getHeader(); - } - - public ByteBuffer getBody() - { - return getContent(0, (int)getSize()); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ProtocolEngineCreator_0_10.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ProtocolEngineCreator_0_10.java deleted file mode 100644 index 08eb06111e..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ProtocolEngineCreator_0_10.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.protocol.v0_10; - -import java.net.InetSocketAddress; -import java.net.SocketAddress; - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Protocol; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.plugin.ProtocolEngineCreator; -import org.apache.qpid.server.security.SubjectCreator; -import org.apache.qpid.transport.ConnectionDelegate; -import org.apache.qpid.transport.network.NetworkConnection; - -@PluggableService -public class ProtocolEngineCreator_0_10 implements ProtocolEngineCreator -{ - - 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 - }; - - - public ProtocolEngineCreator_0_10() - { - } - - public Protocol getVersion() - { - return Protocol.AMQP_0_10; - } - - - public byte[] getHeaderIdentifier() - { - return AMQP_0_10_HEADER; - } - - public ServerProtocolEngine newProtocolEngine(Broker broker, - NetworkConnection network, - AmqpPort port, - Transport transport, - long id) - { - String fqdn = null; - SocketAddress address = network.getLocalAddress(); - if (address instanceof InetSocketAddress) - { - fqdn = ((InetSocketAddress) address).getHostName(); - } - SubjectCreator subjectCreator = port.getAuthenticationProvider().getSubjectCreator(transport.isSecure()); - ConnectionDelegate connDelegate = new ServerConnectionDelegate(broker, fqdn, subjectCreator); - - ServerConnection conn = new ServerConnection(id, broker, port, transport); - - conn.setConnectionDelegate(connDelegate); - conn.setRemoteAddress(network.getRemoteAddress()); - conn.setLocalAddress(network.getLocalAddress()); - - ProtocolEngine_0_10 protocolEngine = new ProtocolEngine_0_10(conn, network); - conn.setProtocolEngine(protocolEngine); - - return protocolEngine; - } - - - private static ProtocolEngineCreator INSTANCE = new ProtocolEngineCreator_0_10(); - - public static ProtocolEngineCreator getInstance() - { - return INSTANCE; - } - - @Override - public String getType() - { - return getVersion().toString(); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ProtocolEngine_0_10.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ProtocolEngine_0_10.java deleted file mode 100755 index dd20ff52ab..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ProtocolEngine_0_10.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.protocol.v0_10; - -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -import javax.security.auth.Subject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.logging.messages.ConnectionMessages; -import org.apache.qpid.server.model.Consumer; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.transport.ByteBufferSender; -import org.apache.qpid.transport.Constant; -import org.apache.qpid.transport.network.Assembler; -import org.apache.qpid.transport.network.InputHandler; -import org.apache.qpid.transport.network.NetworkConnection; - - -public class ProtocolEngine_0_10 extends InputHandler implements ServerProtocolEngine -{ - public static final int MAX_FRAME_SIZE = 64 * 1024 - 1; - private static final Logger _logger = LoggerFactory.getLogger(ProtocolEngine_0_10.class); - - - private NetworkConnection _network; - private long _readBytes; - private long _writtenBytes; - private ServerConnection _connection; - - private long _createTime = System.currentTimeMillis(); - private volatile long _lastReadTime = _createTime; - private volatile long _lastWriteTime = _createTime; - private volatile boolean _transportBlockedForWriting; - - private final AtomicReference _messageAssignmentSuspended = new AtomicReference<>(); - - private final AtomicBoolean _stateChanged = new AtomicBoolean(); - private final AtomicReference> _workListener = new AtomicReference<>(); - - - public ProtocolEngine_0_10(ServerConnection conn, - NetworkConnection network) - { - super(new ServerAssembler(conn)); - _connection = conn; - - if(network != null) - { - setNetworkConnection(network, network.getSender()); - } - } - - @Override - public boolean isMessageAssignmentSuspended() - { - Thread lock = _messageAssignmentSuspended.get(); - return lock != null && _messageAssignmentSuspended.get() != Thread.currentThread(); - } - - @Override - public void setMessageAssignmentSuspended(final boolean messageAssignmentSuspended) - { - _messageAssignmentSuspended.set(messageAssignmentSuspended ? Thread.currentThread() : null); - - for(AMQSessionModel session : _connection.getSessionModels()) - { - for (Consumer consumer : session.getConsumers()) - { - ConsumerImpl consumerImpl = (ConsumerImpl) consumer; - if (!messageAssignmentSuspended) - { - consumerImpl.getTarget().notifyCurrentState(); - } - else - { - // ensure that by the time the method returns, no consumer can be in the process of - // delivering a message. - consumerImpl.getSendLock(); - consumerImpl.releaseSendLock(); - } - } - } - } - - - - public void setNetworkConnection(final NetworkConnection network, final ByteBufferSender sender) - { - if(!getSubject().equals(Subject.getSubject(AccessController.getContext()))) - { - Subject.doAs(getSubject(), new PrivilegedAction() - { - @Override - public Object run() - { - setNetworkConnection(network,sender); - return null; - } - }); - } - else - { - _connection.getEventLogger().message(ConnectionMessages.OPEN(null, null, null, null, false, false, false, false)); - _network = network; - - _connection.setNetworkConnection(network); - ServerDisassembler disassembler = new ServerDisassembler(wrapSender(sender), Constant.MIN_MAX_FRAME_SIZE); - _connection.setSender(disassembler); - _connection.addFrameSizeObserver(disassembler); - // FIXME Two log messages to maintain compatibility with earlier protocol versions - _connection.getEventLogger().message(ConnectionMessages.OPEN(null, "0-10", null, null, false, true, false, false)); - - } - } - - private ByteBufferSender wrapSender(final ByteBufferSender sender) - { - return new ByteBufferSender() - { - @Override - public void send(ByteBuffer msg) - { - _lastWriteTime = System.currentTimeMillis(); - sender.send(msg); - } - - @Override - public void flush() - { - sender.flush(); - - } - - @Override - public void close() - { - sender.close(); - - } - }; - } - - @Override - public long getLastReadTime() - { - return _lastReadTime; - } - - @Override - public long getLastWriteTime() - { - return _lastWriteTime; - } - - public SocketAddress getRemoteAddress() - { - return _network.getRemoteAddress(); - } - - public SocketAddress getLocalAddress() - { - return _network.getLocalAddress(); - } - - public void received(final ByteBuffer buf) - { - _lastReadTime = System.currentTimeMillis(); - if(_connection.getAuthorizedPrincipal() == null && - (_lastReadTime - _createTime) > _connection.getPort().getContextValue(Long.class, - Port.CONNECTION_MAXIMUM_AUTHENTICATION_DELAY) ) - { - Subject.doAs(_connection.getAuthorizedSubject(), new PrivilegedAction() - { - @Override - public Object run() - { - - _logger.warn("Connection has taken more than " - + _connection.getPort() - .getContextValue(Long.class, Port.CONNECTION_MAXIMUM_AUTHENTICATION_DELAY) - + "ms to establish identity. Closing as possible DoS."); - _connection.getEventLogger().message(ConnectionMessages.IDLE_CLOSE()); - _network.close(); - return null; - } - }); - } - super.received(buf); - _connection.receivedComplete(); - } - - public long getReadBytes() - { - return _readBytes; - } - - public long getWrittenBytes() - { - return _writtenBytes; - } - - @Override - public void encryptedTransport() - { - } - - public void writerIdle() - { - _connection.doHeartBeat(); - } - - public void readerIdle() - { - Subject.doAs(_connection.getAuthorizedSubject(), new PrivilegedAction() - { - @Override - public Object run() - { - _connection.getEventLogger().message(ConnectionMessages.IDLE_CLOSE()); - _network.close(); - return null; - } - }); - - } - - public String getAddress() - { - return getRemoteAddress().toString(); - } - - public boolean isDurable() - { - return false; - } - - @Override - public void closed() - { - super.closed(); - } - - public long getCreateTime() - { - return _createTime; - } - - public long getConnectionId() - { - return _connection.getConnectionId(); - } - - @Override - public Subject getSubject() - { - return _connection.getAuthorizedSubject(); - } - - @Override - public boolean isTransportBlockedForWriting() - { - return _transportBlockedForWriting; - } - - @Override - public void setTransportBlockedForWriting(final boolean blocked) - { - _transportBlockedForWriting = blocked; - _connection.transportStateChanged(); - } - - @Override - public void processPending() - { - _connection.processPending(); - - } - - @Override - public boolean hasWork() - { - return _stateChanged.get(); - } - - @Override - public void notifyWork() - { - _stateChanged.set(true); - - final Action listener = _workListener.get(); - if(listener != null) - { - listener.performAction(this); - } - } - - @Override - public void clearWork() - { - _stateChanged.set(false); - } - - @Override - public void setWorkListener(final Action listener) - { - _workListener.set(listener); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerAssembler.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerAssembler.java deleted file mode 100644 index 456c9d36d9..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerAssembler.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.protocol.v0_10; - - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.transport.network.Assembler; -import org.apache.qpid.transport.network.NetworkEvent; - -public class ServerAssembler extends Assembler -{ - private static final Logger LOGGER = LoggerFactory.getLogger(ServerAssembler.class); - - - private final ServerConnection _connection; - - public ServerAssembler(final ServerConnection connection) - { - super(connection); - _connection = connection; - } - - @Override - public void received(final NetworkEvent event) - { - if (!_connection.isIgnoreFutureInput()) - { - super.received(event); - } - else - { - LOGGER.debug("Ignored network event " + event + " as connection is ignoring further input "); - } - } - - -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerConnection.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerConnection.java deleted file mode 100644 index e3b7a9282f..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerConnection.java +++ /dev/null @@ -1,770 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.v0_10; - -import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.CONNECTION_FORMAT; -import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.SOCKET_FORMAT; -import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.USER_FORMAT; -import static org.apache.qpid.transport.Connection.State.CLOSING; - -import java.net.SocketAddress; -import java.security.Principal; -import java.security.PrivilegedAction; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; - -import javax.security.auth.Subject; - -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.connection.ConnectionPrincipal; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.LogSubject; -import org.apache.qpid.server.logging.messages.ConnectionMessages; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.protocol.AMQConnectionModel; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.protocol.SessionModelListener; -import org.apache.qpid.server.security.AuthorizationHolder; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; -import org.apache.qpid.server.stats.StatisticsCounter; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.server.util.ServerScopedRuntimeException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.Connection; -import org.apache.qpid.transport.ConnectionClose; -import org.apache.qpid.transport.ConnectionCloseCode; -import org.apache.qpid.transport.ConnectionCloseOk; -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, AuthorizationHolder -{ - - private final Broker _broker; - private AtomicBoolean _logClosed = new AtomicBoolean(false); - - private final Subject _authorizedSubject = new Subject(); - private Principal _authorizedPrincipal = null; - private final StatisticsCounter _messagesDelivered, _dataDelivered, _messagesReceived, _dataReceived; - private final long _connectionId; - private final Object _reference = new Object(); - private VirtualHostImpl _virtualHost; - private final AmqpPort _port; - private final AtomicLong _lastIoTime = new AtomicLong(); - private boolean _blocking; - private final Transport _transport; - - private final CopyOnWriteArrayList> _connectionCloseTaskList = - new CopyOnWriteArrayList>(); - - private final Queue> _asyncTaskList = - new ConcurrentLinkedQueue<>(); - - private final CopyOnWriteArrayList _sessionListeners = - new CopyOnWriteArrayList(); - - private volatile boolean _stopped; - private int _messageCompressionThreshold; - private final int _maxMessageSize; - - private ServerProtocolEngine _serverProtocolEngine; - private boolean _ignoreFutureInput; - private boolean _ignoreAllButConnectionCloseOk; - - public ServerConnection(final long connectionId, - Broker broker, - final AmqpPort port, - final Transport transport) - { - _connectionId = connectionId; - _authorizedSubject.getPrincipals().add(new ConnectionPrincipal(this)); - _broker = broker; - - _port = port; - _transport = transport; - - int maxMessageSize = port.getContextValue(Integer.class, AmqpPort.PORT_MAX_MESSAGE_SIZE); - _maxMessageSize = (maxMessageSize > 0) ? maxMessageSize : Integer.MAX_VALUE; - - - _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 Object getReference() - { - return _reference; - } - - public Broker getBroker() - { - return _broker; - } - - @Override - protected void invoke(Method method) - { - super.invoke(method); - if (method instanceof ConnectionClose) - { - _ignoreAllButConnectionCloseOk = true; - } - } - - EventLogger getEventLogger() - { - return _virtualHost == null ? _broker.getEventLogger() : _virtualHost.getEventLogger(); - } - - @Override - protected void setState(State state) - { - super.setState(state); - - if (state == State.OPEN) - { - getEventLogger().message(ConnectionMessages.OPEN(getClientId(), - "0-10", - getClientVersion(), - getClientProduct(), - true, - true, - 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)) - { - getEventLogger().message(this, isConnectionLost() ? ConnectionMessages.DROPPED_CONNECTION() : ConnectionMessages.CLOSE()); - } - } - - @Override - public ServerConnectionDelegate getConnectionDelegate() - { - return (ServerConnectionDelegate) super.getConnectionDelegate(); - } - - public void setConnectionDelegate(ServerConnectionDelegate delegate) - { - super.setConnectionDelegate(delegate); - } - - public ServerProtocolEngine getProtocolEngine() - { - return _serverProtocolEngine; - } - - public void setProtocolEngine(final ServerProtocolEngine serverProtocolEngine) - { - _serverProtocolEngine = serverProtocolEngine; - } - - public VirtualHostImpl getVirtualHost() - { - return _virtualHost; - } - - public void setVirtualHost(VirtualHostImpl virtualHost) - { - _virtualHost = virtualHost; - _messageCompressionThreshold = - virtualHost.getContextValue(Integer.class, - Broker.MESSAGE_COMPRESSION_THRESHOLD_SIZE); - - if(_messageCompressionThreshold <= 0) - { - _messageCompressionThreshold = Integer.MAX_VALUE; - } - } - - @Override - public String getVirtualHostName() - { - return _virtualHost == null ? null : _virtualHost.getName(); - } - - @Override - public AmqpPort getPort() - { - return _port; - } - - @Override - public Transport getTransport() - { - return _transport; - } - - @Override - public void stop() - { - _stopped = true; - } - - @Override - public boolean isStopped() - { - return _stopped; - } - - public void closeSessionAsync(final ServerSession session, final AMQConstant cause, final String message) - { - addAsyncTask(new Action() - { - - @Override - public void performAction(final ServerConnection conn) - { - if(!session.isClosing()) - { - 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); - session.invoke(ex); - - session.close(cause, message); - } - } - }); - - } - - public LogSubject getLogSubject() - { - return this; - } - - @Override - public void exception(final Throwable t) - { - try - { - super.exception(t); - } - finally - { - if(t instanceof Error) - { - throw (Error) t; - } - if(t instanceof ServerScopedRuntimeException) - { - throw (ServerScopedRuntimeException) t; - } - } - } - - @Override - public void received(final ProtocolEvent event) - { - _lastIoTime.set(System.currentTimeMillis()); - Subject subject; - if (event.isConnectionControl()) - { - subject = _authorizedSubject; - } - else - { - ServerSession channel = (ServerSession) getSession(event.getChannel()); - if (channel != null) - { - subject = channel.getAuthorizedSubject(); - } - else - { - subject = _authorizedSubject; - } - } - - if(!_ignoreAllButConnectionCloseOk || (event instanceof ConnectionCloseOk)) - { - Subject.doAs(subject, new PrivilegedAction() - { - @Override - public Void run() - { - ServerConnection.super.received(event); - return null; - } - }); - } - } - - public String toLogString() - { - boolean hasVirtualHost = (null != this.getVirtualHost()); - boolean hasClientId = (null != getClientId()); - - if (hasClientId && hasVirtualHost) - { - return "[" + - MessageFormat.format(CONNECTION_FORMAT, - getConnectionId(), - getClientId(), - getRemoteAddressString(), - getVirtualHost().getName()) - + "] "; - } - else if (hasClientId) - { - return "[" + - MessageFormat.format(USER_FORMAT, - getConnectionId(), - getClientId(), - getRemoteAddressString()) - + "] "; - - } - else - { - return "[" + - MessageFormat.format(SOCKET_FORMAT, - getConnectionId(), - getRemoteAddressString()) - + "] "; - } - } - - public void closeAsync(final AMQConstant cause, final String message) - { - - addAsyncTask(new Action() - { - @Override - public void performAction(final ServerConnection object) - { - if(!isClosing()) - { - markAllSessionsClosed(); - - performDeleteTasks(); - - setState(CLOSING); - ConnectionCloseCode replyCode = ConnectionCloseCode.NORMAL; - try - { - replyCode = ConnectionCloseCode.get(cause.getCode()); - } - catch (IllegalArgumentException iae) - { - // Ignore - } - sendConnectionClose(replyCode, message); - } - } - }); - } - - protected void performDeleteTasks() - { - for(Action task : _connectionCloseTaskList) - { - task.performAction(this); - } - } - - public synchronized void block() - { - if(!_blocking) - { - _blocking = true; - for(AMQSessionModel ssn : getSessionModels()) - { - ssn.block(); - } - } - } - - public synchronized void unblock() - { - if(_blocking) - { - _blocking = false; - for(AMQSessionModel ssn : getSessionModels()) - { - ssn.unblock(); - } - } - } - - @Override - public synchronized void registerSession(final Session ssn) - { - super.registerSession(ssn); - sessionAdded((ServerSession)ssn); - if(_blocking) - { - ((ServerSession)ssn).block(); - } - } - - @Override - public synchronized void removeSession(final Session ssn) - { - sessionRemoved((ServerSession)ssn); - super.removeSession(ssn); - } - - public List getSessionModels() - { - List sessions = new ArrayList(); - for (Session ssn : getChannels()) - { - sessions.add((ServerSession) ssn); - } - return sessions; - } - - public void registerMessageDelivered(long messageSize) - { - _messagesDelivered.registerEvent(1L); - _dataDelivered.registerEvent(messageSize); - _virtualHost.registerMessageDelivered(messageSize); - } - - public void registerMessageReceived(long messageSize, long timestamp) - { - _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(); - } - - /** - * @return authorizedSubject - */ - public Subject getAuthorizedSubject() - { - return _authorizedSubject; - } - - /** - * Sets the authorized subject. It also extracts the UsernamePrincipal from the subject - * and caches it for optimisation purposes. - * - * @param authorizedSubject - */ - public void setAuthorizedSubject(final Subject authorizedSubject) - { - if (authorizedSubject == null) - { - _authorizedPrincipal = null; - } - else - { - _authorizedSubject.getPrincipals().addAll(authorizedSubject.getPrincipals()); - - _authorizedPrincipal = AuthenticatedPrincipal.getAuthenticatedPrincipalFromSubject(authorizedSubject); - } - } - - public Principal getAuthorizedPrincipal() - { - return _authorizedPrincipal; - } - - public long getConnectionId() - { - return _connectionId; - } - - public String getRemoteAddressString() - { - return String.valueOf(getRemoteAddress()); - } - - @Override - public String getRemoteProcessPid() - { - return getConnectionDelegate().getRemoteProcessPid(); - } - - @Override - public void closed() - { - performDeleteTasks(); - closeSubscriptions(); - super.closed(); - } - - private void closeSubscriptions() - { - for (Session ssn : getChannels()) - { - ((ServerSession)ssn).unregisterSubscriptions(); - } - } - - private void markAllSessionsClosed() - { - for (Session ssn : getChannels()) - { - final ServerSession session = (ServerSession) ssn; - ((ServerSession) ssn).setClose(true); - session.closed(); - } - } - - public void receivedComplete() - { - for (Session ssn : getChannels()) - { - ((ServerSession)ssn).receivedComplete(); - } - } - - @Override - public void send(ProtocolEvent event) - { - _lastIoTime.set(System.currentTimeMillis()); - super.send(event); - } - - public long getLastIoTime() - { - return _lastIoTime.longValue(); - } - - @Override - public String getClientId() - { - return getConnectionDelegate().getClientId(); - } - - @Override - public String getRemoteContainerName() - { - return getConnectionDelegate().getClientId(); - } - - @Override - public void addSessionListener(final SessionModelListener listener) - { - _sessionListeners.add(listener); - } - - @Override - public void removeSessionListener(final SessionModelListener listener) - { - _sessionListeners.remove(listener); - } - - private void sessionAdded(final AMQSessionModel session) - { - for(SessionModelListener l : _sessionListeners) - { - l.sessionAdded(session); - } - } - - private void sessionRemoved(final AMQSessionModel session) - { - for(SessionModelListener l : _sessionListeners) - { - l.sessionRemoved(session); - } - } - - - @Override - public String getClientVersion() - { - return getConnectionDelegate().getClientVersion(); - } - - @Override - public String getClientProduct() - { - return getConnectionDelegate().getClientProduct(); - } - - public long getSessionCountLimit() - { - return getChannelMax(); - } - - public Principal getPeerPrincipal() - { - return getNetworkConnection().getPeerPrincipal(); - } - - @Override - public void setRemoteAddress(SocketAddress remoteAddress) - { - super.setRemoteAddress(remoteAddress); - } - - @Override - public void setLocalAddress(SocketAddress localAddress) - { - super.setLocalAddress(localAddress); - } - - public void doHeartBeat() - { - super.doHeartBeat(); - } - - @Override - public void addDeleteTask(final Action task) - { - _connectionCloseTaskList.add(task); - } - - private void addAsyncTask(final Action action) - { - _asyncTaskList.add(action); - notifyWork(); - } - - @Override - public void removeDeleteTask(final Action task) - { - _connectionCloseTaskList.remove(task); - } - - public int getMessageCompressionThreshold() - { - return _messageCompressionThreshold; - } - - public int getMaxMessageSize() - { - return _maxMessageSize; - } - - public void transportStateChanged() - { - for (AMQSessionModel ssn : getSessionModels()) - { - ssn.transportStateChanged(); - } - } - - @Override - public void notifyWork() - { - _serverProtocolEngine.notifyWork(); - } - - - @Override - public boolean isMessageAssignmentSuspended() - { - return _serverProtocolEngine.isMessageAssignmentSuspended(); - } - - public void processPending() - { - - for (AMQSessionModel session : getSessionModels()) - { - session.processPending(); - } - - while(_asyncTaskList.peek() != null) - { - Action asyncAction = _asyncTaskList.poll(); - asyncAction.performAction(this); - } - } - - public void closeAndIgnoreFutureInput() - { - _ignoreFutureInput = true; - getSender().close(); - } - - public boolean isIgnoreFutureInput() - { - return _ignoreFutureInput; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerConnectionDelegate.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerConnectionDelegate.java deleted file mode 100644 index b4c0b15dc0..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerConnectionDelegate.java +++ /dev/null @@ -1,443 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.v0_10; - -import static org.apache.qpid.transport.Connection.State.CLOSE_RCVD; - -import java.security.AccessControlException; -import java.security.Principal; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.common.QpidProperties; -import org.apache.qpid.common.ServerPropertyNames; -import org.apache.qpid.properties.ConnectionStartProperties; -import org.apache.qpid.server.configuration.BrokerProperties; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.State; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.protocol.AMQConnectionModel; -import org.apache.qpid.server.security.SubjectCreator; -import org.apache.qpid.server.security.auth.AuthenticationResult.AuthenticationStatus; -import org.apache.qpid.server.security.auth.SubjectAuthenticationResult; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.*; -import org.apache.qpid.transport.network.NetworkConnection; - -public class ServerConnectionDelegate extends ServerDelegate -{ - private static final Logger LOGGER = LoggerFactory.getLogger(ServerConnectionDelegate.class); - - private final Broker _broker; - private final String _localFQDN; - private int _maxNoOfChannels; - private Map _clientProperties; - private final SubjectCreator _subjectCreator; - private int _maximumFrameSize; - - private boolean _compressionSupported; - - public ServerConnectionDelegate(Broker broker, String localFQDN, SubjectCreator subjectCreator) - { - this(createConnectionProperties(broker), Collections.singletonList((Object)"en_US"), broker, localFQDN, subjectCreator); - } - - private ServerConnectionDelegate(Map properties, - List locales, - Broker broker, - String localFQDN, - SubjectCreator subjectCreator) - { - super(properties, (List) subjectCreator.getMechanisms(), locales); - - _broker = broker; - _localFQDN = localFQDN; - _maxNoOfChannels = broker.getConnection_sessionCountLimit(); - _subjectCreator = subjectCreator; - _maximumFrameSize = (int) Math.min(0xffffl, broker.getContextValue(Integer.class, Broker.BROKER_FRAME_SIZE)); - } - - private static List getFeatures(Broker broker) - { - String brokerDisabledFeatures = System.getProperty(BrokerProperties.PROPERTY_DISABLED_FEATURES); - final List features = new ArrayList(); - if (brokerDisabledFeatures == null || !brokerDisabledFeatures.contains(ServerPropertyNames.FEATURE_QPID_JMS_SELECTOR)) - { - features.add(ServerPropertyNames.FEATURE_QPID_JMS_SELECTOR); - } - - return Collections.unmodifiableList(features); - } - - private static Map createConnectionProperties(final Broker broker) - { - final Map map = new HashMap(); - // Federation tag is used by the client to identify the broker instance - map.put(ServerPropertyNames.FEDERATION_TAG, broker.getId().toString()); - final List features = getFeatures(broker); - if (features != null && features.size() > 0) - { - map.put(ServerPropertyNames.QPID_FEATURES, features); - } - - map.put(ServerPropertyNames.PRODUCT, QpidProperties.getProductName()); - map.put(ServerPropertyNames.VERSION, QpidProperties.getReleaseVersion()); - map.put(ServerPropertyNames.QPID_BUILD, QpidProperties.getBuildVersion()); - map.put(ServerPropertyNames.QPID_INSTANCE_NAME, broker.getName()); - map.put(ConnectionStartProperties.QPID_MESSAGE_COMPRESSION_SUPPORTED, String.valueOf(broker.isMessageCompressionEnabled())); - - return map; - } - - public ServerSession getSession(Connection conn, SessionAttach atc) - { - SessionDelegate serverSessionDelegate = new ServerSessionDelegate(); - - ServerSession ssn = new ServerSession(conn, serverSessionDelegate, new Binary(atc.getName()), 0); - - return ssn; - } - - protected SaslServer createSaslServer(Connection conn, String mechanism) throws SaslException - { - return _subjectCreator.createSaslServer(mechanism, _localFQDN, ((ServerConnection) conn).getPeerPrincipal()); - - } - - protected void secure(final SaslServer ss, final Connection conn, final byte[] response) - { - final ServerConnection sconn = (ServerConnection) conn; - final SubjectAuthenticationResult authResult = _subjectCreator.authenticate(ss, response); - - if (AuthenticationStatus.SUCCESS.equals(authResult.getStatus())) - { - tuneAuthorizedConnection(sconn); - sconn.setAuthorizedSubject(authResult.getSubject()); - } - else if (AuthenticationStatus.CONTINUE.equals(authResult.getStatus())) - { - connectionAuthContinue(sconn, authResult.getChallenge()); - } - else - { - connectionAuthFailed(sconn, authResult.getCause()); - } - } - - @Override - public void connectionClose(Connection conn, ConnectionClose close) - { - final ServerConnection sconn = (ServerConnection) conn; - try - { - sconn.logClosed(); - } - finally - { - sconn.closeCode(close); - sconn.setState(CLOSE_RCVD); - sendConnectionCloseOkAndCloseSender(conn); - } - } - - public void connectionOpen(Connection conn, ConnectionOpen open) - { - final ServerConnection sconn = (ServerConnection) conn; - - VirtualHostImpl vhost; - String vhostName; - if(open.hasVirtualHost()) - { - vhostName = open.getVirtualHost(); - } - else - { - vhostName = ""; - } - - AmqpPort port = (AmqpPort) sconn.getPort(); - vhost = port.getVirtualHost(vhostName); - - - - if(vhost != null) - { - if (vhost.getState() != State.ACTIVE) - { - sconn.setState(Connection.State.CLOSING); - final String redirectHost = vhost.getRedirectHost(port); - if(redirectHost == null) - { - sconn.invoke(new ConnectionClose(ConnectionCloseCode.CONNECTION_FORCED, - "Virtual host '" + vhostName + "' is not active")); - } - else - { - sconn.invoke(new ConnectionRedirect(redirectHost, new ArrayList())); - } - return; - } - - sconn.setVirtualHost(vhost); - try - { - if(!vhost.authoriseCreateConnection(sconn)) - { - sconn.setState(Connection.State.CLOSING); - sconn.invoke(new ConnectionClose(ConnectionCloseCode.CONNECTION_FORCED, "Connection not authorized")); - return; - } - } - catch (AccessControlException e) - { - sconn.setState(Connection.State.CLOSING); - sconn.invoke(new ConnectionClose(ConnectionCloseCode.CONNECTION_FORCED, e.getMessage())); - return; - } - - sconn.setState(Connection.State.OPEN); - sconn.invoke(new ConnectionOpenOk(Collections.emptyList())); - } - else - { - sconn.setState(Connection.State.CLOSING); - sconn.invoke(new ConnectionClose(ConnectionCloseCode.INVALID_PATH, - "Unknown virtualhost '" + vhostName + "'")); - } - - } - - @Override - public void connectionTuneOk(final Connection conn, final ConnectionTuneOk ok) - { - ServerConnection sconn = (ServerConnection) conn; - int okChannelMax = ok.getChannelMax(); - int okMaxFrameSize = ok.getMaxFrameSize(); - - if (okChannelMax > getChannelMax()) - { - LOGGER.error("Connection '" + sconn.getConnectionId() + "' being severed, " + - "client connectionTuneOk returned a channelMax (" + okChannelMax + - ") above the server's offered limit (" + getChannelMax() +")"); - - //Due to the error we must forcefully close the connection without negotiation - sconn.closeAndIgnoreFutureInput(); - return; - } - - if(okMaxFrameSize > getFrameMax()) - { - LOGGER.error("Connection '" + sconn.getConnectionId() + "' being severed, " + - "client connectionTuneOk returned a frameMax (" + okMaxFrameSize + - ") above the server's offered limit (" + getFrameMax() +")"); - - //Due to the error we must forcefully close the connection without negotiation - sconn.closeAndIgnoreFutureInput(); - - return; - } - else if(okMaxFrameSize > 0 && okMaxFrameSize < Constant.MIN_MAX_FRAME_SIZE) - { - LOGGER.error("Connection '" + sconn.getConnectionId() + "' being severed, " + - "client connectionTuneOk returned a frameMax (" + okMaxFrameSize + - ") below the minimum permitted size (" + Constant.MIN_MAX_FRAME_SIZE +")"); - - //Due to the error we must forcefully close the connection without negotiation - sconn.closeAndIgnoreFutureInput(); - return; - } - else if(okMaxFrameSize == 0) - { - okMaxFrameSize = getFrameMax(); - } - - final NetworkConnection networkConnection = sconn.getNetworkConnection(); - if(ok.hasHeartbeat()) - { - int heartbeat = ok.getHeartbeat(); - if(heartbeat < 0) - { - heartbeat = 0; - } - - networkConnection.setMaxReadIdle(2 * heartbeat); - networkConnection.setMaxWriteIdle(heartbeat); - - } - else - { - networkConnection.setMaxReadIdle(0); - networkConnection.setMaxWriteIdle(0); - } - - setConnectionTuneOkChannelMax(sconn, okChannelMax); - - conn.setMaxFrameSize(okMaxFrameSize); - } - - @Override - public int getChannelMax() - { - return _maxNoOfChannels; - } - - protected void setChannelMax(int channelMax) - { - _maxNoOfChannels = channelMax; - } - - @Override - protected int getFrameMax() - { - return _maximumFrameSize; - } - - @Override public void sessionDetach(Connection conn, SessionDetach dtc) - { - // To ensure a clean detach, we stop any remaining subscriptions. Stop ensures - // that any in-progress delivery (QueueRunner) is completed before the stop - // completes. - stopAllSubscriptions(conn, dtc); - Session ssn = conn.getSession(dtc.getChannel()); - ((ServerSession)ssn).setClose(true); - super.sessionDetach(conn, dtc); - } - - private void stopAllSubscriptions(Connection conn, SessionDetach dtc) - { - final ServerSession ssn = (ServerSession) conn.getSession(dtc.getChannel()); - final Collection subs = ssn.getSubscriptions(); - for (ConsumerTarget_0_10 subscription_0_10 : subs) - { - subscription_0_10.stop(); - } - } - - - @Override - public void sessionAttach(final Connection conn, final SessionAttach atc) - { - final Session ssn; - - if(isSessionNameUnique(atc.getName(), conn)) - { - super.sessionAttach(conn, atc); - } - else - { - ssn = getSession(conn, atc); - ssn.invoke(new SessionDetached(atc.getName(), SessionDetachCode.SESSION_BUSY)); - ssn.closed(); - } - } - - private boolean isSessionNameUnique(final byte[] name, final Connection conn) - { - final ServerConnection sconn = (ServerConnection) conn; - final Principal authorizedPrincipal = sconn.getAuthorizedPrincipal(); - final String userId = authorizedPrincipal == null ? "" : authorizedPrincipal.getName(); - - final Iterator connections = - ((ServerConnection)conn).getVirtualHost().getConnectionRegistry().getConnections().iterator(); - while(connections.hasNext()) - { - final AMQConnectionModel amqConnectionModel = connections.next(); - if (amqConnectionModel instanceof ServerConnection) - { - ServerConnection otherConnection = (ServerConnection)amqConnectionModel; - - final String userName = amqConnectionModel.getAuthorizedPrincipal() == null - ? "" - : amqConnectionModel.getAuthorizedPrincipal().getName(); - if (userId.equals(userName) && otherConnection.hasSessionWithName(name)) - { - return false; - } - } - } - return true; - } - - @Override - public void connectionStartOk(Connection conn, ConnectionStartOk ok) - { - _clientProperties = ok.getClientProperties(); - if(_clientProperties != null) - { - Object compressionSupported = - _clientProperties.get(ConnectionStartProperties.QPID_MESSAGE_COMPRESSION_SUPPORTED); - if (compressionSupported != null) - { - _compressionSupported = Boolean.parseBoolean(String.valueOf(compressionSupported)); - - } - } - super.connectionStartOk(conn, ok); - } - - public Map getClientProperties() - { - return _clientProperties; - } - - public String getClientId() - { - return _clientProperties == null ? null : (String) _clientProperties.get(ConnectionStartProperties.CLIENT_ID_0_10); - } - - public String getClientVersion() - { - return _clientProperties == null ? null : (String) _clientProperties.get(ConnectionStartProperties.VERSION_0_10); - } - - public String getClientProduct() - { - return _clientProperties == null ? null : (String) _clientProperties.get(ConnectionStartProperties.PRODUCT); - } - - public String getRemoteProcessPid() - { - return (_clientProperties == null || _clientProperties.get(ConnectionStartProperties.PID) == null) ? null : String.valueOf(_clientProperties.get(ConnectionStartProperties.PID)); - } - - @Override - protected int getHeartbeatMax() - { - int delay = (Integer)_broker.getAttribute(Broker.CONNECTION_HEART_BEAT_DELAY); - return delay == 0 ? super.getHeartbeatMax() : delay; - } - - public boolean isCompressionSupported() - { - return _compressionSupported && _broker.isMessageCompressionEnabled(); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerDisassembler.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerDisassembler.java deleted file mode 100644 index a42238a40d..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerDisassembler.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.server.protocol.v0_10; - -import static java.lang.Math.min; -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 java.nio.ByteBuffer; - -import org.apache.qpid.transport.ByteBufferSender; -import org.apache.qpid.transport.FrameSizeObserver; -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.ProtocolEventSender; -import org.apache.qpid.transport.ProtocolHeader; -import org.apache.qpid.transport.SegmentType; -import org.apache.qpid.transport.Struct; -import org.apache.qpid.transport.codec.Encoder; -import org.apache.qpid.transport.network.Frame; - -/** - * Disassembler - */ -public final class ServerDisassembler implements ProtocolEventSender, ProtocolDelegate, FrameSizeObserver -{ - private final ByteBufferSender _sender; - private int _maxPayload; - private final Object _sendLock = new Object(); - private final Encoder _encoder = new ServerEncoder(); - - public ServerDisassembler(ByteBufferSender sender, int maxFrame) - { - _sender = sender; - if (maxFrame <= HEADER_SIZE || maxFrame >= 64 * 1024) - { - throw new IllegalArgumentException("maxFrame must be > HEADER_SIZE and < 64K: " + maxFrame); - } - _maxPayload = maxFrame - HEADER_SIZE; - } - - public void send(ProtocolEvent event) - { - synchronized (_sendLock) - { - 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) - { - ByteBuffer data = ByteBuffer.wrap(new byte[HEADER_SIZE]); - - data.put(0, flags); - data.put(1, type); - data.putShort(2, (short) (size + HEADER_SIZE)); - data.put(5, track); - data.putShort(6, (short) channel); - - - ByteBuffer dup = buf.duplicate(); - dup.limit(dup.position() + size); - buf.position(buf.position() + size); - _sender.send(data); - _sender.send(dup); - - - } - - 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) - { - _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) - { - Encoder enc = _encoder; - enc.init(); - enc.writeUint16(method.getEncodedType()); - if (type == SegmentType.COMMAND) - { - if (method.isSync()) - { - enc.writeUint16(0x0101); - } - else - { - enc.writeUint16(0x0100); - } - } - method.write(enc); - int methodLimit = enc.position(); - - byte flags = FIRST_SEG; - - boolean payload = method.hasPayload(); - if (!payload) - { - flags |= LAST_SEG; - } - - int headerLimit = -1; - if (payload) - { - final Header hdr = method.getHeader(); - if (hdr != null) - { - if (hdr.getDeliveryProperties() != null) - { - enc.writeStruct32(hdr.getDeliveryProperties()); - } - if (hdr.getMessageProperties() != null) - { - enc.writeStruct32(hdr.getMessageProperties()); - } - if (hdr.getNonStandardProperties() != null) - { - for (Struct st : hdr.getNonStandardProperties()) - { - enc.writeStruct32(st); - } - } - } - - headerLimit = enc.position(); - } - synchronized (_sendLock) - { - ByteBuffer buf = enc.underlyingBuffer(); - buf.position(0); - buf.limit(methodLimit); - - fragment(flags, type, method, buf.duplicate()); - if (payload) - { - ByteBuffer body = method.getBody(); - buf.limit(headerLimit); - buf.position(methodLimit); - - fragment(body == null ? LAST_SEG : 0x0, SegmentType.HEADER, method, buf.duplicate()); - if (body != null) - { - fragment(LAST_SEG, SegmentType.BODY, method, body.duplicate()); - } - - } - } - } - - public void error(Void v, ProtocolError error) - { - throw new IllegalArgumentException(String.valueOf(error)); - } - - @Override - public void setMaxFrameSize(final int maxFrame) - { - if (maxFrame <= HEADER_SIZE || maxFrame >= 64*1024) - { - throw new IllegalArgumentException("maxFrame must be > HEADER_SIZE and < 64K: " + maxFrame); - } - this._maxPayload = maxFrame - HEADER_SIZE; - - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerEncoder.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerEncoder.java deleted file mode 100644 index 6437015208..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerEncoder.java +++ /dev/null @@ -1,371 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.v0_10; - -import java.nio.BufferOverflowException; -import java.nio.ByteBuffer; -import java.util.UUID; - -import org.apache.qpid.transport.codec.AbstractEncoder; - - -public final class ServerEncoder extends AbstractEncoder -{ - public static final int DEFAULT_CAPACITY = 8192; - private final int _threshold; - private ByteBuffer _out; - private int _segment; - private int _initialCapacity; - - public ServerEncoder() - { - this(DEFAULT_CAPACITY); - } - - public ServerEncoder(int capacity) - { - _initialCapacity = capacity; - _threshold = capacity/16; - _out = ByteBuffer.allocate(capacity); - _segment = 0; - } - - public void init() - { - _out.position(_out.limit()); - _out.limit(_out.capacity()); - _out = _out.slice(); - if(_out.remaining() < _threshold) - { - _out = ByteBuffer.allocate(_initialCapacity); - } - _segment = 0; - } - - public ByteBuffer buffer() - { - int pos = _out.position(); - _out.position(_segment); - ByteBuffer slice = _out.slice(); - slice.limit(pos - _segment); - _out.position(pos); - return slice; - } - - public int position() - { - return _out.position(); - } - - public ByteBuffer underlyingBuffer() - { - return _out; - } - - private void grow(int size) - { - ByteBuffer old = _out; - int capacity = old.capacity(); - _out = ByteBuffer.allocate(Math.max(Math.max(capacity + size, 2*capacity), _initialCapacity)); - 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); - } - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSession.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSession.java deleted file mode 100644 index 12f79cf203..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSession.java +++ /dev/null @@ -1,1221 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.v0_10; - -import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.CHANNEL_FORMAT; -import static org.apache.qpid.util.Serial.gt; - -import java.security.AccessController; -import java.security.Principal; -import java.security.PrivilegedAction; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentSkipListMap; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; - -import javax.security.auth.Subject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.TransactionTimeoutHelper; -import org.apache.qpid.server.TransactionTimeoutHelper.CloseAction; -import org.apache.qpid.server.connection.SessionPrincipal; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.consumer.ConsumerTarget; -import org.apache.qpid.server.logging.LogMessage; -import org.apache.qpid.server.logging.LogSubject; -import org.apache.qpid.server.logging.messages.ChannelMessages; -import org.apache.qpid.server.logging.subjects.ChannelLogSubject; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.MessageDestination; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfigurationChangeListener; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.Consumer; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.protocol.CapacityChecker; -import org.apache.qpid.server.protocol.ConsumerListener; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.security.AuthorizationHolder; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.StoreException; -import org.apache.qpid.server.util.FutureResult; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.store.TransactionLogResource; -import org.apache.qpid.server.txn.AlreadyKnownDtxException; -import org.apache.qpid.server.txn.AsyncAutoCommitTransaction; -import org.apache.qpid.server.txn.DistributedTransaction; -import org.apache.qpid.server.txn.DtxNotSelectedException; -import org.apache.qpid.server.txn.IncorrectDtxStateException; -import org.apache.qpid.server.txn.JoinAndResumeDtxException; -import org.apache.qpid.server.txn.LocalTransaction; -import org.apache.qpid.server.txn.NotAssociatedDtxException; -import org.apache.qpid.server.txn.RollbackOnlyDtxException; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.txn.SuspendAndFailDtxException; -import org.apache.qpid.server.txn.TimeoutDtxException; -import org.apache.qpid.server.txn.UnknownDtxBranchException; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.server.util.Deletable; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.Binary; -import org.apache.qpid.transport.Connection; -import org.apache.qpid.transport.MessageCreditUnit; -import org.apache.qpid.transport.MessageFlow; -import org.apache.qpid.transport.MessageFlowMode; -import org.apache.qpid.transport.MessageSetFlowMode; -import org.apache.qpid.transport.MessageStop; -import org.apache.qpid.transport.MessageTransfer; -import org.apache.qpid.transport.Method; -import org.apache.qpid.transport.Range; -import org.apache.qpid.transport.RangeSet; -import org.apache.qpid.transport.RangeSetFactory; -import org.apache.qpid.transport.Session; -import org.apache.qpid.transport.SessionDelegate; -import org.apache.qpid.transport.Xid; - -public class ServerSession extends Session - implements AuthorizationHolder, - AMQSessionModel, LogSubject, AsyncAutoCommitTransaction.FutureRecorder, - Deletable - -{ - private static final Logger _logger = LoggerFactory.getLogger(ServerSession.class); - - private static final String NULL_DESTINATION = UUID.randomUUID().toString(); - private static final int PRODUCER_CREDIT_TOPUP_THRESHOLD = 1 << 30; - private static final int UNFINISHED_COMMAND_QUEUE_THRESHOLD = 500; - - private final UUID _id = UUID.randomUUID(); - private final Subject _subject = new Subject(); - private long _createTime = System.currentTimeMillis(); - - private final Set _blockingEntities = Collections.synchronizedSet(new HashSet()); - - private final AtomicBoolean _blocking = new AtomicBoolean(false); - private ChannelLogSubject _logSubject; - private final AtomicInteger _outstandingCredit = new AtomicInteger(UNLIMITED_CREDIT); - private final CheckCapacityAction _checkCapacityAction = new CheckCapacityAction(); - private final CopyOnWriteArrayList _consumerListeners = new CopyOnWriteArrayList(); - private final ConfigurationChangeListener _consumerClosedListener = new ConsumerClosedListener(); - private org.apache.qpid.server.model.Session _modelObject; - private long _blockTime; - private long _blockingTimeout; - private boolean _wireBlockingState; - - public static interface MessageDispositionChangeListener - { - public void onAccept(); - - public void onRelease(boolean setRedelivered); - - public void onReject(); - - public boolean acquire(); - - - } - - private final SortedMap _messageDispositionListenerMap = - new ConcurrentSkipListMap(); - - 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 Map _subscriptions = new ConcurrentHashMap(); - private final CopyOnWriteArrayList> _consumers = new CopyOnWriteArrayList>(); - - private final List> _taskList = new CopyOnWriteArrayList>(); - - private final TransactionTimeoutHelper _transactionTimeoutHelper; - - private AtomicReference _forcedCloseLogMessage = new AtomicReference(); - - private volatile long _uncommittedMessageSize; - private final List> _uncommittedMessages = new ArrayList<>(); - private long _maxUncommittedInMemorySize; - - - public ServerSession(Connection connection, SessionDelegate delegate, Binary name, long expiry) - { - super(connection, delegate, name, expiry); - _transaction = new AsyncAutoCommitTransaction(this.getMessageStore(),this); - _logSubject = new ChannelLogSubject(this); - - _subject.getPrincipals().addAll(((ServerConnection) connection).getAuthorizedSubject().getPrincipals()); - _subject.getPrincipals().add(new SessionPrincipal(this)); - - _transactionTimeoutHelper = new TransactionTimeoutHelper(_logSubject, new CloseAction() - { - @Override - public void doTimeoutAction(String reason) - { - getConnectionModel().closeSessionAsync(ServerSession.this, AMQConstant.RESOURCE_ERROR, reason); - } - }, getVirtualHost()); - - _blockingTimeout = ((ServerConnection)connection).getBroker().getContextValue(Long.class, - Broker.CHANNEL_FLOW_CONTROL_ENFORCEMENT_TIMEOUT); - _maxUncommittedInMemorySize = getVirtualHost().getContextValue(Long.class, org.apache.qpid.server.model.Connection.MAX_UNCOMMITTED_IN_MEMORY_SIZE); - - } - - protected void setState(final State state) - { - if(runningAsSubject()) - { - super.setState(state); - - if (state == State.OPEN) - { - getVirtualHost().getEventLogger().message(ChannelMessages.CREATE()); - } - } - else - { - runAsSubject(new PrivilegedAction() { - - @Override - public Void run() - { - setState(state); - return null; - } - }); - - } - } - - private T runAsSubject(final PrivilegedAction privilegedAction) - { - return Subject.doAs(getAuthorizedSubject(), privilegedAction); - } - - private boolean runningAsSubject() - { - return getAuthorizedSubject().equals(Subject.getSubject(AccessController.getContext())); - } - - private void invokeBlock() - { - invoke(new MessageSetFlowMode("", MessageFlowMode.CREDIT)); - invoke(new MessageStop("")); - } - - private void invokeUnblock() - { - MessageFlow mf = new MessageFlow(); - mf.setUnit(MessageCreditUnit.MESSAGE); - mf.setDestination(""); - _outstandingCredit.set(Integer.MAX_VALUE); - mf.setValue(Integer.MAX_VALUE); - invoke(mf); - } - - - @Override - protected boolean isFull(int id) - { - return isCommandsFull(id); - } - - public int enqueue(final MessageTransferMessage message, - final InstanceProperties instanceProperties, - final MessageDestination exchange) - { - if(_outstandingCredit.get() != UNLIMITED_CREDIT - && _outstandingCredit.decrementAndGet() == (Integer.MAX_VALUE - PRODUCER_CREDIT_TOPUP_THRESHOLD)) - { - _outstandingCredit.addAndGet(PRODUCER_CREDIT_TOPUP_THRESHOLD); - invoke(new MessageFlow("",MessageCreditUnit.MESSAGE, PRODUCER_CREDIT_TOPUP_THRESHOLD)); - } - int enqueues = exchange.send(message, - message.getInitialRoutingAddress(), - instanceProperties, _transaction, _checkCapacityAction - ); - getConnectionModel().registerMessageReceived(message.getSize(), message.getArrivalTime()); - incrementOutstandingTxnsIfNecessary(); - incrementUncommittedMessageSize(message.getStoredMessage()); - return enqueues; - } - - private void resetUncommittedMessages() - { - _uncommittedMessageSize = 0l; - _uncommittedMessages.clear(); - } - - private void incrementUncommittedMessageSize(final StoredMessage handle) - { - if (isTransactional() && !(_transaction instanceof DistributedTransaction)) - { - _uncommittedMessageSize += handle.getMetaData().getContentSize(); - if (_uncommittedMessageSize > getMaxUncommittedInMemorySize()) - { - handle.flowToDisk(); - if(!_uncommittedMessages.isEmpty() || _uncommittedMessageSize == handle.getMetaData().getContentSize()) - { - getVirtualHost().getEventLogger() - .message(_logSubject, ChannelMessages.LARGE_TRANSACTION_WARN(_uncommittedMessageSize)); - } - - if(!_uncommittedMessages.isEmpty()) - { - for (StoredMessage uncommittedHandle : _uncommittedMessages) - { - uncommittedHandle.flowToDisk(); - } - _uncommittedMessages.clear(); - } - } - else - { - _uncommittedMessages.add(handle); - } - } - } - - - public void sendMessage(MessageTransfer xfr, - Runnable postIdSettingAction) - { - getConnectionModel().registerMessageDelivered(xfr.getBodySize()); - invoke(xfr, postIdSettingAction); - } - - 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, final boolean setRedelivered) - { - dispositionChange(ranges, new MessageDispositionAction() - { - public void performAction(MessageDispositionChangeListener listener) - { - listener.onRelease(setRedelivered); - } - }); - } - - public void reject(RangeSet ranges) - { - dispositionChange(ranges, new MessageDispositionAction() - { - public void performAction(MessageDispositionChangeListener listener) - { - listener.onReject(); - } - }); - } - - public RangeSet acquire(RangeSet transfers) - { - RangeSet acquired = RangeSetFactory.createRangeSet(); - - if(!_messageDispositionListenerMap.isEmpty()) - { - Iterator unacceptedMessages = _messageDispositionListenerMap.keySet().iterator(); - Iterator 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) - { - - if(ranges.size() == 1) - { - Range r = ranges.getFirst(); - for(int i = r.getLower(); i <= r.getUpper(); i++) - { - MessageDispositionChangeListener changeListener = _messageDispositionListenerMap.remove(i); - if(changeListener != null) - { - action.performAction(changeListener); - } - } - } - else if(!_messageDispositionListenerMap.isEmpty()) - { - Iterator unacceptedMessages = _messageDispositionListenerMap.keySet().iterator(); - Iterator 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() - { - if(_transaction instanceof LocalTransaction) - { - _transaction.rollback(); - } - else if(_transaction instanceof DistributedTransaction) - { - getVirtualHost().getDtxRegistry().endAssociations(this); - } - - for(MessageDispositionChangeListener listener : _messageDispositionListenerMap.values()) - { - listener.onRelease(true); - } - _messageDispositionListenerMap.clear(); - - for (Action task : _taskList) - { - task.performAction(this); - } - - LogMessage operationalLoggingMessage = _forcedCloseLogMessage.get(); - if (operationalLoggingMessage == null) - { - operationalLoggingMessage = ChannelMessages.CLOSE(); - } - getVirtualHost().getEventLogger().message(getLogSubject(), operationalLoggingMessage); - } - - @Override - protected void awaitClose() - { - // Broker shouldn't block awaiting close - thus do override this method to do nothing - } - - public void acknowledge(final ConsumerTarget_0_10 sub, final MessageInstance entry) - { - _transaction.dequeue(entry.getEnqueueRecord(), - new ServerTransaction.Action() - { - - public void postCommit() - { - sub.deleteAcquired(entry); - } - - public void onRollback() - { - // The client has acknowledge the message and therefore have seen it. - // In the event of rollback, the message must be marked as redelivered. - entry.setRedelivered(); - entry.release(); - } - }); - } - - public Collection getSubscriptions() - { - return _subscriptions.values(); - } - - public void register(String destination, ConsumerTarget_0_10 sub) - { - _subscriptions.put(destination == null ? NULL_DESTINATION : destination, sub); - } - - - public void register(final ConsumerImpl consumerImpl) - { - if(consumerImpl instanceof Consumer) - { - final Consumer consumer = (Consumer) consumerImpl; - _consumers.add(consumer); - consumer.addChangeListener(_consumerClosedListener); - consumerAdded(consumer); - } - } - - public ConsumerTarget_0_10 getSubscription(String destination) - { - return _subscriptions.get(destination == null ? NULL_DESTINATION : destination); - } - - public void unregister(ConsumerTarget_0_10 sub) - { - _subscriptions.remove(sub.getName()); - sub.close(); - - } - - public boolean isTransactional() - { - return _transaction.isTransactional(); - } - - public void selectTx() - { - _transaction = new LocalTransaction(this.getMessageStore()); - _txnStarts.incrementAndGet(); - } - - public void selectDtx() - { - _transaction = new DistributedTransaction(this, getMessageStore(), getVirtualHost()); - - } - - - public void startDtx(Xid xid, boolean join, boolean resume) - throws JoinAndResumeDtxException, - UnknownDtxBranchException, - AlreadyKnownDtxException, - DtxNotSelectedException - { - DistributedTransaction distributedTransaction = assertDtxTransaction(); - distributedTransaction.start(xid, join, resume); - } - - - public void endDtx(Xid xid, boolean fail, boolean suspend) - throws NotAssociatedDtxException, - UnknownDtxBranchException, - DtxNotSelectedException, - SuspendAndFailDtxException, TimeoutDtxException - { - DistributedTransaction distributedTransaction = assertDtxTransaction(); - distributedTransaction.end(xid, fail, suspend); - } - - - public long getTimeoutDtx(Xid xid) - throws UnknownDtxBranchException - { - return getVirtualHost().getDtxRegistry().getTimeout(xid); - } - - - public void setTimeoutDtx(Xid xid, long timeout) - throws UnknownDtxBranchException - { - getVirtualHost().getDtxRegistry().setTimeout(xid, timeout); - } - - - public void prepareDtx(Xid xid) - throws UnknownDtxBranchException, - IncorrectDtxStateException, StoreException, RollbackOnlyDtxException, TimeoutDtxException - { - getVirtualHost().getDtxRegistry().prepare(xid); - } - - public void commitDtx(Xid xid, boolean onePhase) - throws UnknownDtxBranchException, - IncorrectDtxStateException, StoreException, RollbackOnlyDtxException, TimeoutDtxException - { - getVirtualHost().getDtxRegistry().commit(xid, onePhase); - } - - - public void rollbackDtx(Xid xid) - throws UnknownDtxBranchException, - IncorrectDtxStateException, StoreException, TimeoutDtxException - { - getVirtualHost().getDtxRegistry().rollback(xid); - } - - - public void forgetDtx(Xid xid) throws UnknownDtxBranchException, IncorrectDtxStateException - { - getVirtualHost().getDtxRegistry().forget(xid); - } - - public List recoverDtx() - { - return getVirtualHost().getDtxRegistry().recover(); - } - - private DistributedTransaction assertDtxTransaction() throws DtxNotSelectedException - { - if(_transaction instanceof DistributedTransaction) - { - return (DistributedTransaction) _transaction; - } - else - { - throw new DtxNotSelectedException(); - } - } - - - public void commit() - { - _transaction.commit(); - - _txnCommits.incrementAndGet(); - _txnStarts.incrementAndGet(); - decrementOutstandingTxnsIfNecessary(); - resetUncommittedMessages(); - } - - public void rollback() - { - _transaction.rollback(); - - _txnRejects.incrementAndGet(); - _txnStarts.incrementAndGet(); - decrementOutstandingTxnsIfNecessary(); - resetUncommittedMessages(); - } - - - 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 getTxnCommits() - { - return _txnCommits.get(); - } - - public Long getTxnRejects() - { - return _txnRejects.get(); - } - - public int getChannelId() - { - return getChannel(); - } - - public Long getTxnCount() - { - return _txnCount.get(); - } - - public Long getTxnStart() - { - return _txnStarts.get(); - } - - public Principal getAuthorizedPrincipal() - { - return getConnection().getAuthorizedPrincipal(); - } - - public Subject getAuthorizedSubject() - { - return _subject; - } - - public void addDeleteTask(Action task) - { - _taskList.add(task); - } - - public void removeDeleteTask(Action task) - { - _taskList.remove(task); - } - - public Object getReference() - { - return getConnection().getReference(); - } - - public MessageStore getMessageStore() - { - return getVirtualHost().getMessageStore(); - } - - public VirtualHostImpl getVirtualHost() - { - return getConnection().getVirtualHost(); - } - - public boolean isDurable() - { - return false; - } - - - public long getCreateTime() - { - return _createTime; - } - - @Override - public UUID getId() - { - return _id; - } - - public ServerConnection getConnectionModel() - { - return getConnection(); - } - - public String getClientID() - { - return getConnection().getClientId(); - } - - @Override - public ServerConnection getConnection() - { - return (ServerConnection) super.getConnection(); - } - - - public LogSubject getLogSubject() - { - return this; - } - - public void checkTransactionStatus(long openWarn, long openClose, long idleWarn, long idleClose) - { - _transactionTimeoutHelper.checkIdleOrOpenTimes(_transaction, openWarn, openClose, idleWarn, idleClose); - } - - public void block(AMQQueue queue) - { - block(queue, queue.getName()); - } - - public void block() - { - block(this, "** All Queues **"); - } - - - private void block(final Object queue, final String name) - { - synchronized (_blockingEntities) - { - if(_blockingEntities.add(queue)) - { - - if(_blocking.compareAndSet(false,true)) - { - getVirtualHost().getEventLogger().message(_logSubject, ChannelMessages.FLOW_ENFORCED(name)); - if(getState() == State.OPEN) - { - getConnection().notifyWork(); - } - } - - - } - } - } - - public void unblock(AMQQueue queue) - { - unblock((Object)queue); - } - - public void unblock() - { - unblock(this); - } - - private void unblock(final Object queue) - { - if(_blockingEntities.remove(queue) && _blockingEntities.isEmpty()) - { - if(_blocking.compareAndSet(true,false) && !isClosing()) - { - getVirtualHost().getEventLogger().message(_logSubject, ChannelMessages.FLOW_REMOVED()); - getConnection().notifyWork(); - } - } - } - - - boolean blockingTimeoutExceeded() - { - long blockTime = _blockTime; - boolean b = _wireBlockingState && blockTime != 0 && (System.currentTimeMillis() - blockTime) > _blockingTimeout; - return b; - } - - @Override - public void transportStateChanged() - { - for(ConsumerTarget_0_10 consumerTarget : getSubscriptions()) - { - consumerTarget.transportStateChanged(); - } - } - - @Override - public Object getConnectionReference() - { - return getConnection().getReference(); - } - - public String toLogString() - { - long connectionId = super.getConnection() instanceof ServerConnection - ? getConnection().getConnectionId() - : -1; - - String remoteAddress = String.valueOf(getConnection().getRemoteAddress()); - return "[" + - MessageFormat.format(CHANNEL_FORMAT, - connectionId, - getClientID(), - remoteAddress, - getVirtualHost().getName(), - getChannel()) - + "] "; - } - - @Override - public void close(AMQConstant cause, String message) - { - if (cause == null) - { - close(); - } - else - { - close(cause.getCode(), message); - } - } - - void close(int cause, String message) - { - _forcedCloseLogMessage.compareAndSet(null, ChannelMessages.CLOSE_FORCED(cause, message)); - close(); - } - - @Override - public void close() - { - // unregister subscriptions in order to prevent sending of new messages - // to subscriptions with closing session - unregisterSubscriptions(); - if(_modelObject != null) - { - _modelObject.delete(); - } - super.close(); - } - - void unregisterSubscriptions() - { - final Collection subscriptions = getSubscriptions(); - for (ConsumerTarget_0_10 subscription_0_10 : subscriptions) - { - unregister(subscription_0_10); - } - } - - void stopSubscriptions() - { - final Collection subscriptions = getSubscriptions(); - for (ConsumerTarget_0_10 subscription_0_10 : subscriptions) - { - subscription_0_10.stop(); - } - } - - - public void receivedComplete() - { - final Collection subscriptions = getSubscriptions(); - for (ConsumerTarget_0_10 subscription_0_10 : subscriptions) - { - subscription_0_10.flushCreditState(false); - } - awaitCommandCompletion(); - } - - public int getUnacknowledgedMessageCount() - { - return _messageDispositionListenerMap.size(); - } - - public boolean getBlocking() - { - return _blocking.get(); - } - - private final LinkedList _unfinishedCommandsQueue = new LinkedList(); - - public void completeAsyncCommands() - { - AsyncCommand cmd; - while((cmd = _unfinishedCommandsQueue.peek()) != null && cmd.isReadyForCompletion()) - { - cmd.complete(); - _unfinishedCommandsQueue.poll(); - } - while(_unfinishedCommandsQueue.size() > UNFINISHED_COMMAND_QUEUE_THRESHOLD) - { - cmd = _unfinishedCommandsQueue.poll(); - cmd.awaitReadyForCompletion(); - cmd.complete(); - } - } - - - public void awaitCommandCompletion() - { - AsyncCommand cmd; - while((cmd = _unfinishedCommandsQueue.poll()) != null) - { - cmd.awaitReadyForCompletion(); - cmd.complete(); - } - } - - - public Object getAsyncCommandMark() - { - return _unfinishedCommandsQueue.isEmpty() ? null : _unfinishedCommandsQueue.getLast(); - } - - public void recordFuture(final FutureResult future, final ServerTransaction.Action action) - { - _unfinishedCommandsQueue.add(new AsyncCommand(future, action)); - } - - private static class AsyncCommand - { - private final FutureResult _future; - private ServerTransaction.Action _action; - - public AsyncCommand(final FutureResult future, final ServerTransaction.Action action) - { - _future = future; - _action = action; - } - - void awaitReadyForCompletion() - { - _future.waitForCompletion(); - } - - void complete() - { - if(!_future.isComplete()) - { - _future.waitForCompletion(); - } - _action.postCommit(); - _action = null; - } - - boolean isReadyForCompletion() - { - return _future.isComplete(); - } - } - - protected void setClose(boolean close) - { - super.setClose(close); - } - - @Override - public int getConsumerCount() - { - return _subscriptions.values().size(); - } - - @Override - public Collection> getConsumers() - { - - return Collections.unmodifiableCollection(_consumers); - } - - @Override - public void addConsumerListener(final ConsumerListener listener) - { - _consumerListeners.add(listener); - } - - @Override - public void removeConsumerListener(final ConsumerListener listener) - { - _consumerListeners.remove(listener); - } - - @Override - public void setModelObject(final org.apache.qpid.server.model.Session session) - { - _modelObject = session; - } - - @Override - public org.apache.qpid.server.model.Session getModelObject() - { - return _modelObject; - } - - @Override - public long getTransactionStartTime() - { - ServerTransaction serverTransaction = _transaction; - if (serverTransaction.isTransactional()) - { - return serverTransaction.getTransactionStartTime(); - } - else - { - return 0L; - } - } - - @Override - public long getTransactionUpdateTime() - { - ServerTransaction serverTransaction = _transaction; - if (serverTransaction.isTransactional()) - { - return serverTransaction.getTransactionUpdateTime(); - } - else - { - return 0L; - } - } - - private void consumerAdded(Consumer consumer) - { - for(ConsumerListener l : _consumerListeners) - { - l.consumerAdded(consumer); - } - } - - private void consumerRemoved(Consumer consumer) - { - for(ConsumerListener l : _consumerListeners) - { - l.consumerRemoved(consumer); - } - } - - @Override - public void processPending() - { - boolean desiredBlockingState = _blocking.get(); - if (desiredBlockingState != _wireBlockingState) - { - _wireBlockingState = desiredBlockingState; - - if (desiredBlockingState) - { - invokeBlock(); - } - else - { - invokeUnblock(); - } - _blockTime = desiredBlockingState ? System.currentTimeMillis() : 0; - } - - - for(ConsumerTarget target : getSubscriptions()) - { - target.processPending(); - } - } - - - public final long getMaxUncommittedInMemorySize() - { - return _maxUncommittedInMemorySize; - } - - @Override - public int compareTo(AMQSessionModel o) - { - return getId().compareTo(o.getId()); - } - - private class CheckCapacityAction implements Action - { - @Override - public void performAction(final MessageInstance entry) - { - TransactionLogResource queue = entry.getOwningResource(); - if(queue instanceof CapacityChecker) - { - ((CapacityChecker)queue).checkCapacity(ServerSession.this); - } - } - } - - private class ConsumerClosedListener implements ConfigurationChangeListener - { - @Override - public void stateChanged(final ConfiguredObject object, final org.apache.qpid.server.model.State oldState, final org.apache.qpid.server.model.State newState) - { - if(newState == org.apache.qpid.server.model.State.DELETED) - { - consumerRemoved((Consumer)object); - } - } - - @Override - public void childAdded(final ConfiguredObject object, final ConfiguredObject child) - { - - } - - @Override - public void childRemoved(final ConfiguredObject object, final ConfiguredObject child) - { - - } - - @Override - public void attributeSet(final ConfiguredObject object, - final String attributeName, - final Object oldAttributeValue, - final Object newAttributeValue) - { - - } - } -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSessionDelegate.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSessionDelegate.java deleted file mode 100644 index 694dda4da2..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSessionDelegate.java +++ /dev/null @@ -1,1656 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.v0_10; - -import java.nio.ByteBuffer; -import java.security.AccessControlException; -import java.util.Collection; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.common.AMQPFilterTypes; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.exchange.ExchangeImpl; -import org.apache.qpid.server.store.MessageHandle; -import org.apache.qpid.server.virtualhost.VirtualHostUnavailableException; -import org.apache.qpid.server.filter.AMQInvalidArgumentException; -import org.apache.qpid.server.filter.ArrivalTimeFilter; -import org.apache.qpid.server.filter.FilterManager; -import org.apache.qpid.server.filter.FilterManagerFactory; -import org.apache.qpid.server.filter.MessageFilter; -import org.apache.qpid.server.logging.messages.ChannelMessages; -import org.apache.qpid.server.logging.messages.ExchangeMessages; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.MessageDestination; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.message.MessageSource; -import org.apache.qpid.server.model.ExclusivityPolicy; -import org.apache.qpid.server.model.LifetimePolicy; -import org.apache.qpid.server.model.NoFactoryForTypeException; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.UnknownConfiguredObjectException; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.QueueArgumentsConverter; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.StoreException; -import org.apache.qpid.server.util.FutureResult; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.txn.AlreadyKnownDtxException; -import org.apache.qpid.server.txn.DtxNotSelectedException; -import org.apache.qpid.server.txn.IncorrectDtxStateException; -import org.apache.qpid.server.txn.JoinAndResumeDtxException; -import org.apache.qpid.server.txn.NotAssociatedDtxException; -import org.apache.qpid.server.txn.RollbackOnlyDtxException; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.txn.SuspendAndFailDtxException; -import org.apache.qpid.server.txn.TimeoutDtxException; -import org.apache.qpid.server.txn.UnknownDtxBranchException; -import org.apache.qpid.server.util.ServerScopedRuntimeException; -import org.apache.qpid.server.virtualhost.ExchangeExistsException; -import org.apache.qpid.server.virtualhost.ExchangeIsAlternateException; -import org.apache.qpid.server.virtualhost.QueueExistsException; -import org.apache.qpid.server.virtualhost.RequiredExchangeException; -import org.apache.qpid.server.virtualhost.ReservedExchangeNameException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.*; - -public class ServerSessionDelegate extends SessionDelegate -{ - private static final Logger LOGGER = LoggerFactory.getLogger(ServerSessionDelegate.class); - - public ServerSessionDelegate() - { - - } - - @Override - public void command(Session session, Method method) - { - try - { - if(!session.isClosing()) - { - Object asyncCommandMark = ((ServerSession)session).getAsyncCommandMark(); - super.command(session, method, false); - Object newOutstanding = ((ServerSession)session).getAsyncCommandMark(); - if(newOutstanding == null || newOutstanding == asyncCommandMark) - { - session.processed(method); - } - - if(newOutstanding != null) - { - ((ServerSession)session).completeAsyncCommands(); - } - - if (method.isSync()) - { - ((ServerSession)session).awaitCommandCompletion(); - session.flushProcessed(); - } - } - } - catch(RuntimeException e) - { - LOGGER.error("Exception processing command", e); - exception(session, method, ExecutionErrorCode.INTERNAL_ERROR, "Exception processing command: " + e); - if(e instanceof ServerScopedRuntimeException) - { - throw e; - } - } - } - - @Override - public void messageAccept(Session session, MessageAccept method) - { - final ServerSession serverSession = (ServerSession) session; - serverSession.accept(method.getTransfers()); - if(!serverSession.isTransactional()) - { - serverSession.recordFuture(FutureResult.IMMEDIATE_FUTURE, - new CommandProcessedAction(serverSession, method)); - } - } - - @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(), method.getSetRedelivered()); - } - - @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 - Correct code should read like - if not hasAcceptMode() exception ILLEGAL_ARGUMENT "Accept-mode not supplied" - else if not method.hasAcquireMode() exception ExecutionErrorCode.ILLEGAL_ARGUMENT, "Acquire-mode not supplied" - */ - if(!method.hasAcceptMode()) - { - method.setAcceptMode(MessageAcceptMode.EXPLICIT); - } - if(!method.hasAcquireMode()) - { - method.setAcquireMode(MessageAcquireMode.PRE_ACQUIRED); - - } - - 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 destination '"+destination+"'"); - } - else - { - String queueName = method.getQueue(); - VirtualHostImpl vhost = getVirtualHost(session); - - final Collection sources = new HashSet<>(); - final MessageSource queue = vhost.getMessageSource(queueName); - if(queue != null) - { - sources.add(queue); - } - else if(vhost.getContextValue(Boolean.class, "qpid.enableMultiQueueConsumers") - && method.getArguments() != null - && method.getArguments().get("x-multiqueue") instanceof Collection) - { - for(Object object : (Collection)method.getArguments().get("x-multiqueue")) - { - String sourceName = String.valueOf(object); - sourceName = sourceName.trim(); - if(sourceName.length() != 0) - { - MessageSource source = vhost.getMessageSource(sourceName); - if(source == null) - { - sources.clear(); - break; - } - else - { - sources.add(source); - } - } - } - queueName = method.getArguments().get("x-multiqueue").toString(); - } - - if(sources.isEmpty()) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, "Queue: " + queueName + " not found"); - } - else if(!verifySessionAccess((ServerSession) session, sources)) - { - exception(session,method,ExecutionErrorCode.RESOURCE_LOCKED, "Exclusive Queue: " + queueName + " owned exclusively by another session"); - } - else - { - ServerProtocolEngine serverProtocolEngine = getServerConnection(session).getProtocolEngine(); - FlowCreditManager_0_10 creditManager = new WindowCreditManager(0L,0L, serverProtocolEngine); - - FilterManager filterManager = null; - try - { - filterManager = FilterManagerFactory.createManager(method.getArguments()); - } - catch (AMQInvalidArgumentException amqe) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "Exception Creating FilterManager"); - return; - } - - - if(method.hasArguments() && method.getArguments().containsKey(AMQPFilterTypes.REPLAY_PERIOD.toString())) - { - Object value = method.getArguments().get(AMQPFilterTypes.REPLAY_PERIOD.toString()); - final long period; - if(value instanceof Number) - { - period = ((Number)value).longValue(); - } - else if(value instanceof String) - { - try - { - period = Long.parseLong(value.toString()); - } - catch (NumberFormatException e) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "Cannot parse value " + value + " as a number for filter " + AMQPFilterTypes.REPLAY_PERIOD.toString()); - return; - } - } - else - { - exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "Cannot parse value " + value + " as a number for filter " + AMQPFilterTypes.REPLAY_PERIOD.toString()); - return; - } - final long startingFrom = System.currentTimeMillis() - (1000l * period); - if(filterManager == null) - { - filterManager = new FilterManager(); - } - MessageFilter filter = new ArrivalTimeFilter(startingFrom, period == 0); - filterManager.add(filter.getName(), filter); - - } - - - ConsumerTarget_0_10 target = new ConsumerTarget_0_10((ServerSession)session, destination, - method.getAcceptMode(), - method.getAcquireMode(), - MessageFlowMode.WINDOW, - creditManager, - method.getArguments() - ); - - ((ServerSession)session).register(destination, target); - try - { - EnumSet options = EnumSet.noneOf(ConsumerImpl.Option.class); - if(method.getAcquireMode() == MessageAcquireMode.PRE_ACQUIRED) - { - options.add(ConsumerImpl.Option.ACQUIRES); - } - if(method.getAcquireMode() != MessageAcquireMode.NOT_ACQUIRED || method.getAcceptMode() == MessageAcceptMode.EXPLICIT) - { - options.add(ConsumerImpl.Option.SEES_REQUEUES); - } - if(method.getExclusive()) - { - options.add(ConsumerImpl.Option.EXCLUSIVE); - } - for(MessageSource source : sources) - { - ((ServerSession) session).register( - source.addConsumer(target, - filterManager, - MessageTransferMessage.class, - destination, - options)); - } - } - catch (AMQQueue.ExistingExclusiveConsumer existing) - { - exception(session, method, ExecutionErrorCode.RESOURCE_LOCKED, "Queue has an exclusive consumer"); - } - catch (AMQQueue.ExistingConsumerPreventsExclusive exclusive) - { - exception(session, method, ExecutionErrorCode.RESOURCE_LOCKED, "Queue has an existing consumer - can't subscribe exclusively"); - } - catch (AccessControlException e) - { - exception(session, method, ExecutionErrorCode.UNAUTHORIZED_ACCESS, e.getMessage()); - } - catch (MessageSource.ConsumerAccessRefused consumerAccessRefused) - { - exception(session, method, ExecutionErrorCode.RESOURCE_LOCKED, "Queue has an incompatible exclusivity policy"); - } - } - } - } - } - - protected boolean verifySessionAccess(final ServerSession session, final Collection queues) - { - for(MessageSource source : queues) - { - if(!verifySessionAccess(session, source)) - { - return false; - } - } - return true; - } - - protected boolean verifySessionAccess(final ServerSession session, final MessageSource queue) - { - return queue.verifySessionAccess(session); - } - - @Override - public void messageTransfer(Session ssn, final MessageTransfer xfr) - { - ServerSession serverSession = (ServerSession) ssn; - if(serverSession.blockingTimeoutExceeded()) - { - getVirtualHost(ssn).getEventLogger().message(ChannelMessages.FLOW_CONTROL_IGNORED()); - - serverSession.close(AMQConstant.MESSAGE_TOO_LARGE, - "Session flow control was requested, but not enforced by sender"); - } - else if(xfr.getBodySize() > serverSession.getConnection().getMaxMessageSize()) - { - exception(ssn, xfr, ExecutionErrorCode.RESOURCE_LIMIT_EXCEEDED, - "Message size of " + xfr.getBodySize() + " greater than allowed maximum of " + serverSession.getConnection().getMaxMessageSize()); - } - else - { - final MessageDestination destination = getDestinationForMessage(ssn, xfr); - - final DeliveryProperties delvProps = - xfr.getHeader() == null ? null : xfr.getHeader().getDeliveryProperties(); - if (delvProps != null && delvProps.hasTtl() && !delvProps.hasExpiration()) - { - delvProps.setExpiration(System.currentTimeMillis() + delvProps.getTtl()); - } - - final MessageMetaData_0_10 messageMetaData = new MessageMetaData_0_10(xfr); - - final VirtualHostImpl virtualHost = getVirtualHost(ssn); - try - { - virtualHost.getSecurityManager() - .authorisePublish(messageMetaData.isImmediate(), - messageMetaData.getRoutingKey(), - destination.getName(), - virtualHost.getName()); - } - catch (AccessControlException e) - { - ExecutionErrorCode errorCode = ExecutionErrorCode.UNAUTHORIZED_ACCESS; - exception(ssn, xfr, errorCode, e.getMessage()); - - return; - } - - final MessageStore store = virtualHost.getMessageStore(); - final StoredMessage storeMessage = createStoreMessage(xfr, messageMetaData, store); - final MessageTransferMessage message = - new MessageTransferMessage(storeMessage, serverSession.getReference()); - MessageReference reference = message.newReference(); - - try - { - final InstanceProperties instanceProperties = new InstanceProperties() - { - @Override - public Object getProperty(final Property prop) - { - switch (prop) - { - case EXPIRATION: - return message.getExpiration(); - case IMMEDIATE: - return message.isImmediate(); - case MANDATORY: - return (delvProps == null || !delvProps.getDiscardUnroutable()) - && xfr.getAcceptMode() == MessageAcceptMode.EXPLICIT; - case PERSISTENT: - return message.isPersistent(); - case REDELIVERED: - return delvProps.getRedelivered(); - } - return null; - } - }; - - int enqueues = serverSession.enqueue(message, instanceProperties, destination); - - if (enqueues == 0) - { - if ((delvProps == null || !delvProps.getDiscardUnroutable()) - && xfr.getAcceptMode() == MessageAcceptMode.EXPLICIT) - { - RangeSet rejects = RangeSetFactory.createRangeSet(); - rejects.add(xfr.getId()); - MessageReject reject = new MessageReject(rejects, MessageRejectCode.UNROUTABLE, "Unroutable"); - ssn.invoke(reject); - } - else - { - virtualHost.getEventLogger().message(ExchangeMessages.DISCARDMSG(destination.getName(), - messageMetaData.getRoutingKey())); - } - } - - if (serverSession.isTransactional()) - { - serverSession.processed(xfr); - } - else - { - serverSession.recordFuture(FutureResult.IMMEDIATE_FUTURE, - new CommandProcessedAction(serverSession, xfr)); - } - } - catch (VirtualHostUnavailableException e) - { - getServerConnection(serverSession).closeAsync(AMQConstant.CONNECTION_FORCED, e.getMessage()); - } - finally - { - reference.release(); - } - - } - } - - private StoredMessage createStoreMessage(final MessageTransfer xfr, - final MessageMetaData_0_10 messageMetaData, final MessageStore store) - { - final MessageHandle addedMessage = store.addMessage(messageMetaData); - ByteBuffer body = xfr.getBody(); - if(body != null) - { - addedMessage.addContent(body); - } - final StoredMessage storedMessage = addedMessage.allContentAdded(); - return storedMessage; - } - - @Override - public void messageCancel(Session session, MessageCancel method) - { - String destination = method.getDestination(); - - ConsumerTarget_0_10 sub = ((ServerSession)session).getSubscription(destination); - - if(sub == null) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, "not-found: destination '"+destination+"'"); - } - else - { - ((ServerSession)session).unregister(sub); - } - } - - @Override - public void messageFlush(Session session, MessageFlush method) - { - String destination = method.getDestination(); - - ConsumerTarget_0_10 sub = ((ServerSession)session).getSubscription(destination); - - if(sub == null) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, "not-found: destination '"+destination+"'"); - } - else - { - sub.flush(); - } - } - - @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 dtxSelect(Session session, DtxSelect method) - { - // TODO - check current tx mode - ((ServerSession)session).selectDtx(); - } - - @Override - public void dtxStart(Session session, DtxStart method) - { - XaResult result = new XaResult(); - result.setStatus(DtxXaStatus.XA_OK); - try - { - ((ServerSession)session).startDtx(method.getXid(), method.getJoin(), method.getResume()); - session.executionResult(method.getId(), result); - } - catch(JoinAndResumeDtxException e) - { - exception(session, method, ExecutionErrorCode.COMMAND_INVALID, e.getMessage()); - } - catch(UnknownDtxBranchException e) - { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Unknown xid " + method.getXid()); - } - catch(AlreadyKnownDtxException e) - { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Xid already started an neither join nor " + - "resume set" + method.getXid()); - } - catch(DtxNotSelectedException e) - { - exception(session, method, ExecutionErrorCode.COMMAND_INVALID, e.getMessage()); - } - - } - - @Override - public void dtxEnd(Session session, DtxEnd method) - { - XaResult result = new XaResult(); - result.setStatus(DtxXaStatus.XA_OK); - try - { - try - { - ((ServerSession) session).endDtx(method.getXid(), method.getFail(), method.getSuspend()); - } - catch (TimeoutDtxException e) - { - result.setStatus(DtxXaStatus.XA_RBTIMEOUT); - } - session.executionResult(method.getId(), result); - } - catch(UnknownDtxBranchException e) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_STATE, e.getMessage()); - } - catch(NotAssociatedDtxException e) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_STATE, e.getMessage()); - } - catch(DtxNotSelectedException e) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_STATE, e.getMessage()); - } - catch(SuspendAndFailDtxException e) - { - exception(session, method, ExecutionErrorCode.COMMAND_INVALID, e.getMessage()); - } - - } - - @Override - public void dtxCommit(Session session, DtxCommit method) - { - XaResult result = new XaResult(); - result.setStatus(DtxXaStatus.XA_OK); - try - { - try - { - ((ServerSession)session).commitDtx(method.getXid(), method.getOnePhase()); - } - catch (RollbackOnlyDtxException e) - { - result.setStatus(DtxXaStatus.XA_RBROLLBACK); - } - catch (TimeoutDtxException e) - { - result.setStatus(DtxXaStatus.XA_RBTIMEOUT); - } - session.executionResult(method.getId(), result); - } - catch(UnknownDtxBranchException e) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, e.getMessage()); - } - catch(IncorrectDtxStateException e) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_STATE, e.getMessage()); - } - catch(StoreException e) - { - exception(session, method, ExecutionErrorCode.INTERNAL_ERROR, e.getMessage()); - throw e; - } - } - - @Override - public void dtxForget(Session session, DtxForget method) - { - try - { - ((ServerSession)session).forgetDtx(method.getXid()); - } - catch(UnknownDtxBranchException e) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, e.getMessage()); - } - catch(IncorrectDtxStateException e) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_STATE, e.getMessage()); - } - - } - - @Override - public void dtxGetTimeout(Session session, DtxGetTimeout method) - { - GetTimeoutResult result = new GetTimeoutResult(); - try - { - result.setTimeout(((ServerSession) session).getTimeoutDtx(method.getXid())); - session.executionResult(method.getId(), result); - } - catch(UnknownDtxBranchException e) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, e.getMessage()); - } - } - - @Override - public void dtxPrepare(Session session, DtxPrepare method) - { - XaResult result = new XaResult(); - result.setStatus(DtxXaStatus.XA_OK); - try - { - try - { - ((ServerSession)session).prepareDtx(method.getXid()); - } - catch (RollbackOnlyDtxException e) - { - result.setStatus(DtxXaStatus.XA_RBROLLBACK); - } - catch (TimeoutDtxException e) - { - result.setStatus(DtxXaStatus.XA_RBTIMEOUT); - } - session.executionResult((int) method.getId(), result); - } - catch(UnknownDtxBranchException e) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, e.getMessage()); - } - catch(IncorrectDtxStateException e) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_STATE, e.getMessage()); - } - catch(StoreException e) - { - exception(session, method, ExecutionErrorCode.INTERNAL_ERROR, e.getMessage()); - throw e; - } - } - - @Override - public void dtxRecover(Session session, DtxRecover method) - { - RecoverResult result = new RecoverResult(); - List inDoubt = ((ServerSession)session).recoverDtx(); - result.setInDoubt(inDoubt); - session.executionResult(method.getId(), result); - } - - @Override - public void dtxRollback(Session session, DtxRollback method) - { - - XaResult result = new XaResult(); - result.setStatus(DtxXaStatus.XA_OK); - try - { - try - { - ((ServerSession)session).rollbackDtx(method.getXid()); - } - catch (TimeoutDtxException e) - { - result.setStatus(DtxXaStatus.XA_RBTIMEOUT); - } - session.executionResult(method.getId(), result); - } - catch(UnknownDtxBranchException e) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, e.getMessage()); - } - catch(IncorrectDtxStateException e) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_STATE, e.getMessage()); - } - catch(StoreException e) - { - exception(session, method, ExecutionErrorCode.INTERNAL_ERROR, e.getMessage()); - throw e; - } - } - - @Override - public void dtxSetTimeout(Session session, DtxSetTimeout method) - { - try - { - ((ServerSession)session).setTimeoutDtx(method.getXid(), method.getTimeout()); - } - catch(UnknownDtxBranchException e) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, e.getMessage()); - } - } - - @Override - public void executionSync(final Session ssn, final ExecutionSync sync) - { - ((ServerSession)ssn).awaitCommandCompletion(); - super.executionSync(ssn, sync); - } - - @Override - public void exchangeDeclare(Session session, ExchangeDeclare method) - { - String exchangeName = method.getExchange(); - VirtualHostImpl virtualHost = getVirtualHost(session); - - //we must check for any unsupported arguments present and throw not-implemented - if(method.hasArguments()) - { - Map args = method.getArguments(); - //QPID-3392: currently we don't support any! - if(!args.isEmpty()) - { - exception(session, method, ExecutionErrorCode.NOT_IMPLEMENTED, "Unsupported exchange argument(s) found " + args.keySet().toString()); - return; - } - } - if(nameNullOrEmpty(method.getExchange())) - { - // special case handling to fake the existence of the default exchange for 0-10 - if(!ExchangeDefaults.DIRECT_EXCHANGE_CLASS.equals(method.getType())) - { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, - "Attempt to redeclare default exchange " - + " of type " + ExchangeDefaults.DIRECT_EXCHANGE_CLASS - + " to " + method.getType() +"."); - } - if(!nameNullOrEmpty(method.getAlternateExchange())) - { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, - "Attempt to set alternate exchange of the default exchange " - + " to " + method.getAlternateExchange() +"."); - } - } - else - { - if(method.getPassive()) - { - - ExchangeImpl exchange = getExchange(session, exchangeName); - - if(exchange == null) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, "not-found: exchange-name '" + exchangeName + "'"); - } - else - { - if (!exchange.getType().equals(method.getType()) - && (method.getType() != null && method.getType().length() > 0)) - { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Attempt to redeclare exchange: " - + exchangeName + " of type " + exchange.getType() + " to " + method.getType() + "."); - } - } - } - else - { - - try - { - Map attributes = new HashMap(); - - attributes.put(org.apache.qpid.server.model.Exchange.ID, null); - attributes.put(org.apache.qpid.server.model.Exchange.NAME, method.getExchange()); - attributes.put(org.apache.qpid.server.model.Exchange.TYPE, method.getType()); - attributes.put(org.apache.qpid.server.model.Exchange.DURABLE, method.getDurable()); - attributes.put(org.apache.qpid.server.model.Exchange.LIFETIME_POLICY, - method.getAutoDelete() ? LifetimePolicy.DELETE_ON_NO_LINKS : LifetimePolicy.PERMANENT); - attributes.put(org.apache.qpid.server.model.Exchange.ALTERNATE_EXCHANGE, method.getAlternateExchange()); - virtualHost.createExchange(attributes); - } - catch(ReservedExchangeNameException e) - { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Attempt to declare exchange: " - + exchangeName + " which begins with reserved name or prefix."); - } - catch(UnknownConfiguredObjectException e) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, - "Unknown alternate exchange " + e.getName()); - } - catch(NoFactoryForTypeException e) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, "Unknown Exchange Type: " + method.getType()); - } - catch(ExchangeExistsException e) - { - ExchangeImpl exchange = e.getExistingExchange(); - if(!exchange.getType().equals(method.getType())) - { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, - "Attempt to redeclare exchange: " + exchangeName - + " of type " + exchange.getType() - + " to " + method.getType() +"."); - } - else if(method.hasAlternateExchange() - && (exchange.getAlternateExchange() == null || - !method.getAlternateExchange().equals(exchange.getAlternateExchange().getName()))) - { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, - "Attempt to change alternate exchange of: " + exchangeName - + " from " + exchange.getAlternateExchange() - + " to " + method.getAlternateExchange() +"."); - } - } - catch (AccessControlException e) - { - exception(session, method, ExecutionErrorCode.UNAUTHORIZED_ACCESS, e.getMessage()); - } - - - } - } - } - - 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); - - ((ServerSession)session).close(errorCode.getValue(), description); - } - - private ExchangeImpl getExchange(Session session, String exchangeName) - { - return getVirtualHost(session).getExchange(exchangeName); - } - - private MessageDestination getDestinationForMessage(Session ssn, MessageTransfer xfr) - { - VirtualHostImpl virtualHost = getVirtualHost(ssn); - - MessageDestination destination; - if(xfr.hasDestination()) - { - destination = virtualHost.getMessageDestination(xfr.getDestination()); - if(destination == null) - { - destination = virtualHost.getDefaultDestination(); - } - } - else - { - destination = virtualHost.getDefaultDestination(); - } - return destination; - } - - private VirtualHostImpl getVirtualHost(Session session) - { - ServerConnection conn = getServerConnection(session); - return conn.getVirtualHost(); - } - - private ServerConnection getServerConnection(Session session) - { - return (ServerConnection) session.getConnection(); - } - - @Override - public void exchangeDelete(Session session, ExchangeDelete method) - { - VirtualHostImpl virtualHost = getVirtualHost(session); - - try - { - if (nameNullOrEmpty(method.getExchange())) - { - exception(session, method, ExecutionErrorCode.INVALID_ARGUMENT, "Delete not allowed for default exchange"); - return; - } - - ExchangeImpl exchange = getExchange(session, method.getExchange()); - - if(exchange == null) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, "No such exchange '" + method.getExchange() + "'"); - } - else - { - virtualHost.removeExchange(exchange, !method.getIfUnused()); - } - } - catch (ExchangeIsAlternateException e) - { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Exchange in use as an alternate exchange"); - } - catch (RequiredExchangeException e) - { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Exchange '"+method.getExchange()+"' cannot be deleted"); - } - catch (AccessControlException e) - { - exception(session, method, ExecutionErrorCode.UNAUTHORIZED_ACCESS, e.getMessage()); - } - } - - private boolean nameNullOrEmpty(String name) - { - if(name == null || name.length() == 0) - { - return true; - } - - return false; - } - - @Override - public void exchangeQuery(Session session, ExchangeQuery method) - { - - ExchangeQueryResult result = new ExchangeQueryResult(); - - - final String exchangeName = method.getName(); - - if(nameNullOrEmpty(exchangeName)) - { - // Fake the existence of the "default" exchange for 0-10 - result.setDurable(true); - result.setType(ExchangeDefaults.DIRECT_EXCHANGE_CLASS); - result.setNotFound(false); - } - else - { - ExchangeImpl exchange = getExchange(session, exchangeName); - - if(exchange != null) - { - result.setDurable(exchange.isDurable()); - result.setType(exchange.getType()); - result.setNotFound(false); - } - else - { - result.setNotFound(true); - } - } - session.executionResult((int) method.getId(), result); - } - - @Override - public void exchangeBind(Session session, ExchangeBind method) - { - - VirtualHostImpl virtualHost = getVirtualHost(session); - - if (!method.hasQueue()) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "queue not set"); - } - else - { - final String exchangeName = method.getExchange(); - if (nameNullOrEmpty(exchangeName)) - { - exception(session, method, ExecutionErrorCode.INVALID_ARGUMENT, "Bind not allowed for default exchange"); - } - else - { - //TODO - here because of non-compliant python tests - // should raise exception ILLEGAL_ARGUMENT "binding-key not set" - if (!method.hasBindingKey()) - { - method.setBindingKey(method.getQueue()); - } - AMQQueue queue = virtualHost.getQueue(method.getQueue()); - ExchangeImpl exchange = virtualHost.getExchange(exchangeName); - 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: '" + exchangeName + "' not found"); - } - else if(exchange.getType().equals(ExchangeDefaults.HEADERS_EXCHANGE_CLASS) && (!method.hasArguments() || method.getArguments() == null || !method.getArguments().containsKey("x-match"))) - { - exception(session, method, ExecutionErrorCode.INTERNAL_ERROR, "Bindings to an exchange of type " + ExchangeDefaults.HEADERS_EXCHANGE_CLASS + " require an x-match header"); - } - else - { - if (!exchange.isBound(method.getBindingKey(), method.getArguments(), queue)) - { - try - { - exchange.addBinding(method.getBindingKey(), queue, method.getArguments()); - } - catch (AccessControlException e) - { - exception(session, method, ExecutionErrorCode.UNAUTHORIZED_ACCESS, e.getMessage()); - } - } - else - { - // todo - } - } - - - } - } - - - - } - - @Override - public void exchangeUnbind(Session session, ExchangeUnbind method) - { - VirtualHostImpl virtualHost = getVirtualHost(session); - - if (!method.hasQueue()) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "queue not set"); - } - else if (nameNullOrEmpty(method.getExchange())) - { - exception(session, method, ExecutionErrorCode.INVALID_ARGUMENT, "Unbind not allowed for default exchange"); - } - else if (!method.hasBindingKey()) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "binding-key not set"); - } - else - { - AMQQueue queue = virtualHost.getQueue(method.getQueue()); - ExchangeImpl exchange = virtualHost.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 - { - if(exchange.hasBinding(method.getBindingKey(), queue)) - { - exchange.deleteBinding(method.getBindingKey(), queue); - } - } - catch (AccessControlException e) - { - exception(session, method, ExecutionErrorCode.UNAUTHORIZED_ACCESS, e.getMessage()); - } - } - } - } - - @Override - public void exchangeBound(Session session, ExchangeBound method) - { - - ExchangeBoundResult result = new ExchangeBoundResult(); - VirtualHostImpl virtualHost = getVirtualHost(session); - ExchangeImpl exchange; - AMQQueue queue; - boolean isDefaultExchange; - if(!nameNullOrEmpty(method.getExchange())) - { - isDefaultExchange = false; - exchange = virtualHost.getExchange(method.getExchange()); - - if(exchange == null) - { - result.setExchangeNotFound(true); - } - } - else - { - isDefaultExchange = true; - exchange = null; - } - - if(isDefaultExchange) - { - // fake the existence of the "default" exchange for 0-10 - if(method.hasQueue()) - { - queue = getQueue(session, method.getQueue()); - - if(queue == null) - { - result.setQueueNotFound(true); - } - else - { - if(method.hasBindingKey()) - { - if(!method.getBindingKey().equals(method.getQueue())) - { - result.setKeyNotMatched(true); - } - } - } - } - else if(method.hasBindingKey()) - { - if(getQueue(session, method.getBindingKey()) == null) - { - result.setKeyNotMatched(true); - } - } - - if(method.hasArguments() && !method.getArguments().isEmpty()) - { - result.setArgsNotMatched(true); - } - - - } - else 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(queueMatched) - { - final boolean keyMatched = exchange.isBound(method.getBindingKey(), queue); - result.setKeyNotMatched(!keyMatched); - if(method.hasArguments()) - { - if(keyMatched) - { - result.setArgsNotMatched(!exchange.isBound(method.getBindingKey(), method.getArguments(), queue)); - } - else - { - result.setArgsNotMatched(!exchange.isBound(method.getArguments(), queue)); - } - } - } - else - { - boolean keyMatched = exchange.isBound(method.getBindingKey()); - result.setKeyNotMatched(!keyMatched); - if(method.hasArguments()) - { - if(keyMatched) - { - result.setArgsNotMatched(!exchange.isBound(method.getBindingKey(), method.getArguments())); - } - else - { - result.setArgsNotMatched(!exchange.isBound(method.getArguments())); - } - } - } - - } - else if (method.hasArguments()) - { - if(queueMatched) - { - result.setArgsNotMatched(!exchange.isBound(method.getArguments(), queue)); - } - else - { - result.setArgsNotMatched(!exchange.isBound(method.getArguments())); - } - } - - } - else if(exchange != null && method.hasBindingKey()) - { - final boolean keyMatched = exchange.isBound(method.getBindingKey()); - result.setKeyNotMatched(!keyMatched); - - if(method.hasArguments()) - { - if(keyMatched) - { - result.setArgsNotMatched(!exchange.isBound(method.getBindingKey(), method.getArguments())); - } - else - { - result.setArgsNotMatched(!exchange.isBound(method.getArguments())); - } - } - - - } - - } - else if(exchange != null && method.hasBindingKey()) - { - final boolean keyMatched = exchange.isBound(method.getBindingKey()); - result.setKeyNotMatched(!keyMatched); - - if(method.hasArguments()) - { - if(keyMatched) - { - result.setArgsNotMatched(!exchange.isBound(method.getBindingKey(), method.getArguments())); - } - else - { - result.setArgsNotMatched(!exchange.isBound(method.getArguments())); - } - } - - } - else if(exchange != null && method.hasArguments()) - { - result.setArgsNotMatched(!exchange.isBound(method.getArguments())); - } - - - session.executionResult((int) method.getId(), result); - - - } - - private AMQQueue getQueue(Session session, String queue) - { - return getVirtualHost(session).getQueue(queue); - } - - @Override - public void queueDeclare(Session session, final QueueDeclare method) - { - - final VirtualHostImpl virtualHost = getVirtualHost(session); - - String queueName = method.getQueue(); - AMQQueue queue; - //TODO: do we need to check that the queue already exists with exactly the same "configuration"? - - final boolean exclusive = method.getExclusive(); - final boolean autoDelete = method.getAutoDelete(); - - if(method.getPassive()) - { - queue = virtualHost.getQueue(queueName); - - if (queue == null) - { - String description = "Queue: " + queueName + " not found on VirtualHost(" + virtualHost + ")."; - ExecutionErrorCode errorCode = ExecutionErrorCode.NOT_FOUND; - - exception(session, method, errorCode, description); - - } - else if (exclusive) - { - if (queue.getExclusive() == ExclusivityPolicy.NONE) - { - String description = "Cannot passively declare queue ('" + queueName + "')" - + " as exclusive as queue with same name is" + - " already declared as non-exclusive"; - ExecutionErrorCode errorCode = ExecutionErrorCode.RESOURCE_LOCKED; - exception(session, method, errorCode, description); - - } - else if (!verifySessionAccess((ServerSession) session, queue)) - { - String description = "Cannot passively declare queue('" + queueName + "')," - + " as exclusive queue with same name " - + "declared on another session"; - ExecutionErrorCode errorCode = ExecutionErrorCode.RESOURCE_LOCKED; - exception(session, method, errorCode, description); - } - } - } - else - { - - try - { - - final String alternateExchangeName = method.getAlternateExchange(); - - - final Map arguments = QueueArgumentsConverter.convertWireArgsToModel(method.getArguments()); - - if(alternateExchangeName != null && alternateExchangeName.length() != 0) - { - arguments.put(Queue.ALTERNATE_EXCHANGE, alternateExchangeName); - } - - final UUID id = UUID.randomUUID(); - - arguments.put(Queue.ID, id); - arguments.put(Queue.NAME, queueName); - - LifetimePolicy lifetime; - if(autoDelete) - { - lifetime = exclusive ? LifetimePolicy.DELETE_ON_SESSION_END - : LifetimePolicy.DELETE_ON_NO_OUTBOUND_LINKS; - } - else - { - lifetime = LifetimePolicy.PERMANENT; - } - - arguments.put(Queue.LIFETIME_POLICY, lifetime); - - ExclusivityPolicy exclusivityPolicy = exclusive ? ExclusivityPolicy.SESSION : ExclusivityPolicy.NONE; - - - arguments.put(Queue.DURABLE, method.getDurable()); - - arguments.put(Queue.EXCLUSIVE, exclusivityPolicy); - - queue = virtualHost.createQueue(arguments); - - } - catch(QueueExistsException qe) - { - queue = qe.getExistingQueue(); - if (!verifySessionAccess((ServerSession) session, queue)) - { - 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); - } - } - catch (AccessControlException e) - { - exception(session, method, ExecutionErrorCode.UNAUTHORIZED_ACCESS, e.getMessage()); - } - } - } - - @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(!verifySessionAccess((ServerSession) session, queue)) - { - 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 - { - VirtualHostImpl virtualHost = getVirtualHost(session); - - try - { - virtualHost.removeQueue(queue); - } - catch (AccessControlException e) - { - exception(session, method, ExecutionErrorCode.UNAUTHORIZED_ACCESS, e.getMessage()); - } - } - } - } - } - - @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 (AccessControlException e) - { - exception(session, method, ExecutionErrorCode.UNAUTHORIZED_ACCESS, e.getMessage()); - } - } - } - } - - @Override - public void queueQuery(Session session, QueueQuery method) - { - QueueQueryResult result = new QueueQueryResult(); - - AMQQueue queue = getQueue(session, method.getQueue()); - - if(queue != null) - { - result.setQueue(queue.getName()); - result.setDurable(queue.isDurable()); - result.setExclusive(queue.isExclusive()); - result.setAutoDelete(queue.getLifetimePolicy() != LifetimePolicy.PERMANENT); - Map arguments = new LinkedHashMap(); - Collection availableAttrs = queue.getAvailableAttributes(); - - for(String attrName : availableAttrs) - { - arguments.put(attrName, queue.getAttribute(attrName)); - } - result.setArguments(QueueArgumentsConverter.convertModelArgsToWire(arguments)); - result.setMessageCount(queue.getQueueDepthMessages()); - result.setSubscriberCount(queue.getConsumerCount()); - - } - - - session.executionResult((int) method.getId(), result); - - } - - @Override - public void messageSetFlowMode(Session session, MessageSetFlowMode sfm) - { - String destination = sfm.getDestination(); - - ConsumerTarget_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(); - - ConsumerTarget_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(); - - ConsumerTarget_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) - { - ServerSession serverSession = (ServerSession)session; - - serverSession.stopSubscriptions(); - serverSession.onClose(); - serverSession.unregisterSubscriptions(); - } - - @Override - public void detached(Session session) - { - closed(session); - } - - private static class CommandProcessedAction implements ServerTransaction.Action - { - private final ServerSession _serverSession; - private final Method _method; - - public CommandProcessedAction(final ServerSession serverSession, final Method xfr) - { - _serverSession = serverSession; - _method = xfr; - } - - public void postCommit() - { - _serverSession.processed(_method); - } - - public void onRollback() - { - } - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/WindowCreditManager.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/WindowCreditManager.java deleted file mode 100644 index 6c400b8e24..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/WindowCreditManager.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.v0_10; - - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.flow.AbstractFlowCreditManager; - -public class WindowCreditManager extends AbstractFlowCreditManager implements FlowCreditManager_0_10 -{ - private static final Logger LOGGER = LoggerFactory.getLogger(WindowCreditManager.class); - private final ServerProtocolEngine _serverProtocolEngine; - - private volatile long _bytesCreditLimit; - private volatile long _messageCreditLimit; - - private volatile long _bytesUsed; - private volatile long _messageUsed; - - public WindowCreditManager(long bytesCreditLimit, - long messageCreditLimit, - ServerProtocolEngine serverProtocolEngine) - { - _serverProtocolEngine = serverProtocolEngine; - _bytesCreditLimit = bytesCreditLimit; - _messageCreditLimit = messageCreditLimit; - setSuspended(!hasCredit()); - - } - - public long getMessageCreditLimit() - { - return _messageCreditLimit; - } - - 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) - { - _messageUsed -= messageCredit; - if(_messageUsed < 0L) - { - LOGGER.error("Message credit used value was negative: "+ _messageUsed); - _messageUsed = 0; - } - - boolean notifyIncrease = true; - - if(_messageCreditLimit > 0L) - { - notifyIncrease = (_messageUsed != _messageCreditLimit); - } - - _bytesUsed -= bytesCredit; - if(_bytesUsed < 0L) - { - LOGGER.error("Bytes credit used value was negative: "+ _messageUsed); - _bytesUsed = 0; - } - - if(_bytesCreditLimit > 0L) - { - notifyIncrease = notifyIncrease && bytesCredit>0; - - if(notifyIncrease) - { - notifyIncreaseBytesCredit(); - } - } - - setSuspended(!hasCredit()); - } - - - - public synchronized boolean hasCredit() - { - return (_bytesCreditLimit < 0L || _bytesCreditLimit > _bytesUsed) - && (_messageCreditLimit < 0L || _messageCreditLimit > _messageUsed) - && !_serverProtocolEngine.isTransportBlockedForWriting(); - } - - public synchronized boolean useCreditForMessage(final long msgSize) - { - if (_serverProtocolEngine.isTransportBlockedForWriting()) - { - setSuspended(true); - return false; - } - else if(_messageCreditLimit >= 0L) - { - if(_messageUsed < _messageCreditLimit) - { - if(_bytesCreditLimit < 0L) - { - _messageUsed++; - - return true; - } - else if(_bytesUsed + msgSize <= _bytesCreditLimit) - { - _messageUsed++; - _bytesUsed += msgSize; - - return true; - } - else - { - return false; - } - } - else - { - setSuspended(true); - return false; - } - } - else if(_bytesCreditLimit >= 0L) - { - if(_bytesUsed + msgSize <= _bytesCreditLimit) - { - _bytesUsed += msgSize; - - return true; - } - else - { - return false; - } - - } - else - { - return true; - } - - } - - - 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/qpid/java/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/ServerSessionTest.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/ServerSessionTest.java deleted file mode 100644 index 2fc76d4f02..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/ServerSessionTest.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.server.protocol.v0_10; - -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.transport.Binary; -import org.apache.qpid.transport.ExecutionErrorCode; -import org.apache.qpid.transport.ExecutionException; -import org.apache.qpid.transport.MessageTransfer; -import org.apache.qpid.transport.Method; - -public class ServerSessionTest extends QpidTestCase -{ - - private VirtualHostImpl _virtualHost; - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _virtualHost = BrokerTestHelper.createVirtualHost(getName()); - } - - @Override - public void tearDown() throws Exception - { - try - { - if (_virtualHost != null) - { - _virtualHost.close(); - } - } - finally - { - BrokerTestHelper.tearDown(); - super.tearDown(); - } - } - - public void testCompareTo() throws Exception - { - final Broker broker = mock(Broker.class); - when(broker.getContextValue(eq(Long.class), eq(Broker.CHANNEL_FLOW_CONTROL_ENFORCEMENT_TIMEOUT))).thenReturn(0l); - - AmqpPort amqpPort = mock(AmqpPort.class); - when(amqpPort.getContextValue(eq(Integer.class), eq(AmqpPort.PORT_MAX_MESSAGE_SIZE))).thenReturn(AmqpPort.DEFAULT_MAX_MESSAGE_SIZE); - - ServerConnection connection = new ServerConnection(1, broker, amqpPort, Transport.TCP); - connection.setVirtualHost(_virtualHost); - ServerSession session1 = new ServerSession(connection, new ServerSessionDelegate(), - new Binary(getName().getBytes()), 0); - - // create a session with the same name but on a different connection - ServerConnection connection2 = new ServerConnection(2, broker, amqpPort, Transport.TCP); - connection2.setVirtualHost(_virtualHost); - ServerSession session2 = new ServerSession(connection2, new ServerSessionDelegate(), - new Binary(getName().getBytes()), 0); - - assertFalse("Unexpected compare result", session1.compareTo(session2) == 0); - assertEquals("Unexpected compare result", 0, session1.compareTo(session1)); - } - - public void testOverlargeMessageTest() throws Exception - { - final Broker broker = mock(Broker.class); - when(broker.getContextValue(eq(Long.class), eq(Broker.CHANNEL_FLOW_CONTROL_ENFORCEMENT_TIMEOUT))).thenReturn(0l); - - AmqpPort port = mock(AmqpPort.class); - when(port.getContextValue(eq(Integer.class), eq(AmqpPort.PORT_MAX_MESSAGE_SIZE))).thenReturn(1024); - ServerConnection connection = new ServerConnection(1, broker, port, Transport.TCP); - connection.setVirtualHost(_virtualHost); - final List invokedMethods = new ArrayList<>(); - ServerSession session = new ServerSession(connection, new ServerSessionDelegate(), - new Binary(getName().getBytes()), 0) - { - @Override - public void invoke(final Method m) - { - invokedMethods.add(m); - } - }; - - ServerSessionDelegate delegate = new ServerSessionDelegate(); - - MessageTransfer xfr = new MessageTransfer(); - xfr.setBody(new byte[2048]); - delegate.messageTransfer(session, xfr); - - assertFalse("No methods invoked - expecting at least 1", invokedMethods.isEmpty()); - Method firstInvoked = invokedMethods.get(0); - assertTrue("First invoked method not execution error", firstInvoked instanceof ExecutionException); - assertEquals(ExecutionErrorCode.RESOURCE_LIMIT_EXCEEDED, ((ExecutionException)firstInvoked).getErrorCode()); - - invokedMethods.clear(); - - // test the boundary condition - - xfr.setBody(new byte[1024]); - delegate.messageTransfer(session, xfr); - - assertTrue("Methods invoked when not expecting any", invokedMethods.isEmpty()); - } - - -} diff --git a/qpid/java/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/WindowCreditManagerTest.java b/qpid/java/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/WindowCreditManagerTest.java deleted file mode 100644 index b9f013d253..0000000000 --- a/qpid/java/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/WindowCreditManagerTest.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.protocol.v0_10; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.test.utils.QpidTestCase; - -public class WindowCreditManagerTest extends QpidTestCase -{ - private WindowCreditManager _creditManager; - private ServerProtocolEngine _protocolEngine; - - protected void setUp() throws Exception - { - super.setUp(); - - _protocolEngine = mock(ServerProtocolEngine.class); - when(_protocolEngine.isTransportBlockedForWriting()).thenReturn(false); - - _creditManager = new WindowCreditManager(0l, 0l, _protocolEngine); - } - - /** - * Tests that after the credit limit is cleared (e.g. from a message.stop command), credit is - * restored (e.g. from completed MessageTransfer) without increasing the available credit, and - * more credit is added, that the 'used' count is correct and the proper values for bytes - * and message credit are returned along with appropriate 'hasCredit' results (QPID-3592). - */ - public void testRestoreCreditDecrementsUsedCountAfterCreditClear() - { - assertEquals("unexpected credit value", 0, _creditManager.getMessageCredit()); - assertEquals("unexpected credit value", 0, _creditManager.getBytesCredit()); - - //give some message credit - _creditManager.addCredit(1, 0); - assertFalse("Manager should not 'haveCredit' due to having 0 bytes credit", _creditManager.hasCredit()); - assertEquals("unexpected credit value", 1, _creditManager.getMessageCredit()); - assertEquals("unexpected credit value", 0, _creditManager.getBytesCredit()); - - //give some bytes credit - _creditManager.addCredit(0, 1); - assertTrue("Manager should 'haveCredit'", _creditManager.hasCredit()); - assertEquals("unexpected credit value", 1, _creditManager.getMessageCredit()); - assertEquals("unexpected credit value", 1, _creditManager.getBytesCredit()); - - //use all the credit - _creditManager.useCreditForMessage(1); - assertEquals("unexpected credit value", 0, _creditManager.getBytesCredit()); - assertEquals("unexpected credit value", 0, _creditManager.getMessageCredit()); - assertFalse("Manager should not 'haveCredit'", _creditManager.hasCredit()); - - //clear credit out (eg from a message.stop command) - _creditManager.clearCredit(); - assertEquals("unexpected credit value", 0, _creditManager.getBytesCredit()); - assertEquals("unexpected credit value", 0, _creditManager.getMessageCredit()); - assertFalse("Manager should not 'haveCredit'", _creditManager.hasCredit()); - - //restore credit (e.g the original message transfer command got completed) - //this should not increase credit, because it is now limited to 0 - _creditManager.restoreCredit(1, 1); - assertEquals("unexpected credit value", 0, _creditManager.getBytesCredit()); - assertEquals("unexpected credit value", 0, _creditManager.getMessageCredit()); - assertFalse("Manager should not 'haveCredit'", _creditManager.hasCredit()); - - //give more credit to open the window again - _creditManager.addCredit(1, 1); - assertEquals("unexpected credit value", 1, _creditManager.getBytesCredit()); - assertEquals("unexpected credit value", 1, _creditManager.getMessageCredit()); - assertTrue("Manager should 'haveCredit'", _creditManager.hasCredit()); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/pom.xml b/qpid/java/broker-plugins/amqp-0-8-protocol/pom.xml deleted file mode 100644 index e09a3ba922..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/pom.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - - 4.0.0 - - - org.apache.qpid - qpid-java-build - 0.32-SNAPSHOT - ../../pom.xml - - - qpid-broker-plugins-amqp-0-8-protocol - Qpid AMQP 0-8 Protocol Broker Plug-in - AMQP 0-8, 0-9 and 0-9-1 protocol broker plug-in - - - ${basedir}/../ - - - - - org.apache.qpid - qpid-broker-core - ${project.version} - provided - - - - org.apache.qpid - qpid-broker-codegen - ${project.version} - true - - - - log4j - log4j - ${log4j-version} - - - - - org.apache.qpid - qpid-test-utils - ${project.version} - test - - - - org.apache.qpid - qpid-broker-core - ${project.version} - test-jar - test - - - - - - - diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQChannel.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQChannel.java deleted file mode 100644 index 522408910d..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQChannel.java +++ /dev/null @@ -1,3670 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.v0_8; - -import static org.apache.qpid.transport.util.Functions.hex; - -import java.nio.ByteBuffer; -import java.security.AccessControlException; -import java.security.PrivilegedAction; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; - -import javax.security.auth.Subject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQConnectionException; -import org.apache.qpid.AMQException; -import org.apache.qpid.common.AMQPFilterTypes; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.*; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.TransactionTimeoutHelper; -import org.apache.qpid.server.TransactionTimeoutHelper.CloseAction; -import org.apache.qpid.server.configuration.BrokerProperties; -import org.apache.qpid.server.connection.SessionPrincipal; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.consumer.ConsumerTarget; -import org.apache.qpid.server.exchange.ExchangeImpl; -import org.apache.qpid.server.filter.AMQInvalidArgumentException; -import org.apache.qpid.server.filter.ArrivalTimeFilter; -import org.apache.qpid.server.filter.FilterManager; -import org.apache.qpid.server.filter.FilterManagerFactory; -import org.apache.qpid.server.filter.Filterable; -import org.apache.qpid.server.filter.MessageFilter; -import org.apache.qpid.server.flow.FlowCreditManager; -import org.apache.qpid.server.logging.LogMessage; -import org.apache.qpid.server.logging.LogSubject; -import org.apache.qpid.server.logging.messages.ChannelMessages; -import org.apache.qpid.server.logging.messages.ExchangeMessages; -import org.apache.qpid.server.logging.subjects.ChannelLogSubject; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.MessageDestination; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.message.MessageSource; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfigurationChangeListener; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.Connection; -import org.apache.qpid.server.model.Consumer; -import org.apache.qpid.server.model.Exchange; -import org.apache.qpid.server.model.ExclusivityPolicy; -import org.apache.qpid.server.model.LifetimePolicy; -import org.apache.qpid.server.model.NoFactoryForTypeException; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.Session; -import org.apache.qpid.server.model.State; -import org.apache.qpid.server.model.UnknownConfiguredObjectException; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.protocol.CapacityChecker; -import org.apache.qpid.server.protocol.ConsumerListener; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.QueueArgumentsConverter; -import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.store.MessageHandle; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.store.TransactionLogResource; -import org.apache.qpid.server.txn.AsyncAutoCommitTransaction; -import org.apache.qpid.server.txn.LocalTransaction; -import org.apache.qpid.server.txn.LocalTransaction.ActivityTimeAccessor; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.server.util.FutureResult; -import org.apache.qpid.server.virtualhost.ExchangeExistsException; -import org.apache.qpid.server.virtualhost.ExchangeIsAlternateException; -import org.apache.qpid.server.virtualhost.QueueExistsException; -import org.apache.qpid.server.virtualhost.RequiredExchangeException; -import org.apache.qpid.server.virtualhost.ReservedExchangeNameException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.TransportException; - -public class AMQChannel - implements AMQSessionModel, - AsyncAutoCommitTransaction.FutureRecorder, - ServerChannelMethodProcessor -{ - public static final int DEFAULT_PREFETCH = 4096; - - private static final Logger _logger = LoggerFactory.getLogger(AMQChannel.class); - private final DefaultQueueAssociationClearingTask - _defaultQueueAssociationClearingTask = new DefaultQueueAssociationClearingTask(); - - //TODO use Broker property to configure message authorization requirements - private boolean _messageAuthorizationRequired = Boolean.getBoolean(BrokerProperties.PROPERTY_MSG_AUTH); - - private final int _channelId; - - - private final Pre0_10CreditManager _creditManager; - private final FlowCreditManager _noAckCreditManager; - - /** - * The delivery tag is unique per channel. This is pre-incremented before putting into the deliver frame so that - * value of this represents the last tag sent out - */ - private long _deliveryTag = 0; - - /** A channel has a default queue (the last declared) that is used when no queue name is explicitly set */ - private volatile 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. */ - private final Map _tag2SubscriptionTargetMap = new HashMap(); - - private final MessageStore _messageStore; - - private final LinkedList _unfinishedCommandsQueue = new LinkedList(); - - private UnacknowledgedMessageMap _unacknowledgedMessageMap = new UnacknowledgedMessageMapImpl(DEFAULT_PREFETCH); - - 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 AMQProtocolEngine _connection; - private AtomicBoolean _closing = new AtomicBoolean(false); - - private final Set _blockingEntities = Collections.synchronizedSet(new HashSet()); - - private final AtomicBoolean _blocking = new AtomicBoolean(false); - - - private LogSubject _logSubject; - private volatile boolean _rollingBack; - - private List _resendList = new ArrayList(); - private static final - AMQShortString IMMEDIATE_DELIVERY_REPLY_TEXT = new AMQShortString("Immediate delivery is not possible."); - - private final ClientDeliveryMethod _clientDeliveryMethod; - - private final TransactionTimeoutHelper _transactionTimeoutHelper; - private final UUID _id = UUID.randomUUID(); - - private final List> _taskList = - new CopyOnWriteArrayList>(); - - - private final CapacityCheckAction _capacityCheckAction = new CapacityCheckAction(); - private final ImmediateAction _immediateAction = new ImmediateAction(); - private Subject _subject; - private final CopyOnWriteArrayList> _consumers = new CopyOnWriteArrayList>(); - private final ConfigurationChangeListener _consumerClosedListener = new ConsumerClosedListener(); - private final CopyOnWriteArrayList _consumerListeners = new CopyOnWriteArrayList(); - private Session _modelObject; - private long _blockTime; - private long _blockingTimeout; - private boolean _confirmOnPublish; - private long _confirmedMessageCounter; - private volatile long _uncommittedMessageSize; - private final List> _uncommittedMessages = new ArrayList<>(); - private long _maxUncommittedInMemorySize; - - private boolean _wireBlockingState; - - public AMQChannel(AMQProtocolEngine connection, int channelId, final MessageStore messageStore) - { - _creditManager = new Pre0_10CreditManager(0l,0l, connection); - _noAckCreditManager = new NoAckCreditManager(connection); - - _connection = connection; - _channelId = channelId; - - _subject = new Subject(false, connection.getAuthorizedSubject().getPrincipals(), - connection.getAuthorizedSubject().getPublicCredentials(), - connection.getAuthorizedSubject().getPrivateCredentials()); - _subject.getPrincipals().add(new SessionPrincipal(this)); - _maxUncommittedInMemorySize = connection.getVirtualHost().getContextValue(Long.class, Connection.MAX_UNCOMMITTED_IN_MEMORY_SIZE); - _logSubject = new ChannelLogSubject(this); - - _messageStore = messageStore; - _blockingTimeout = connection.getBroker().getContextValue(Long.class, - Broker.CHANNEL_FLOW_CONTROL_ENFORCEMENT_TIMEOUT); - // by default the session is non-transactional - _transaction = new AsyncAutoCommitTransaction(_messageStore, this); - - _clientDeliveryMethod = connection.createDeliveryMethod(_channelId); - - _transactionTimeoutHelper = new TransactionTimeoutHelper(_logSubject, new CloseAction() - { - @Override - public void doTimeoutAction(String reason) - { - try - { - closeConnection(reason); - } - catch (AMQException e) - { - throw new ConnectionScopedRuntimeException(e); - } - } - }, getVirtualHost()); - - Subject.doAs(_subject, new PrivilegedAction() - { - @Override - public Object run() - { - getVirtualHost().getEventLogger().message(ChannelMessages.CREATE()); - - return null; - } - }); - - } - - private boolean performGet(final AMQQueue queue, - final boolean acks) - throws MessageSource.ExistingConsumerPreventsExclusive, - MessageSource.ExistingExclusiveConsumer, MessageSource.ConsumerAccessRefused - { - - final FlowCreditManager singleMessageCredit = new MessageOnlyCreditManager(1L); - - final GetDeliveryMethod getDeliveryMethod = - new GetDeliveryMethod(singleMessageCredit, queue); - final RecordDeliveryMethod getRecordMethod = new RecordDeliveryMethod() - { - - public void recordMessageDelivery(final ConsumerImpl sub, - final MessageInstance entry, - final long deliveryTag) - { - addUnacknowledgedMessage(entry, deliveryTag, null); - } - }; - - ConsumerTarget_0_8 target; - EnumSet options = EnumSet.of(ConsumerImpl.Option.TRANSIENT, ConsumerImpl.Option.ACQUIRES, - ConsumerImpl.Option.SEES_REQUEUES); - if (acks) - { - - target = ConsumerTarget_0_8.createAckTarget(this, - AMQShortString.EMPTY_STRING, null, - singleMessageCredit, getDeliveryMethod, getRecordMethod); - } - else - { - target = ConsumerTarget_0_8.createGetNoAckTarget(this, - AMQShortString.EMPTY_STRING, null, - singleMessageCredit, getDeliveryMethod, getRecordMethod); - } - - ConsumerImpl sub = queue.addConsumer(target, null, AMQMessage.class, "", options); - sub.flush(); - sub.close(); - return getDeliveryMethod.hasDeliveredMessage(); - - - } - - /** Sets this channel to be part of a local transaction */ - public void setLocalTransactional() - { - _transaction = new LocalTransaction(_messageStore, new ActivityTimeAccessor() - { - @Override - public long getActivityTime() - { - return _connection.getLastReceivedTime(); - } - }); - _txnStarts.incrementAndGet(); - } - - public boolean isTransactional() - { - return _transaction.isTransactional(); - } - - public void receivedComplete() - { - sync(); - } - - 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 getTxnCommits() - { - return _txnCommits.get(); - } - - public Long getTxnRejects() - { - return _txnRejects.get(); - } - - public Long getTxnCount() - { - return _txnCount.get(); - } - - public Long getTxnStart() - { - return _txnStarts.get(); - } - - public int getChannelId() - { - return _channelId; - } - - public void setPublishFrame(MessagePublishInfo info, final MessageDestination e) - { - String routingKey = info.getRoutingKey() == null ? null : info.getRoutingKey().asString(); - VirtualHostImpl virtualHost = getVirtualHost(); - SecurityManager securityManager = virtualHost.getSecurityManager(); - - securityManager.authorisePublish(info.isImmediate(), routingKey, e.getName(), virtualHost.getName()); - - _currentMessage = new IncomingMessage(info); - _currentMessage.setMessageDestination(e); - } - - public void publishContentHeader(ContentHeaderBody contentHeaderBody) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Content header received on channel " + _channelId); - } - - _currentMessage.setContentHeaderBody(contentHeaderBody); - - deliverCurrentMessageIfComplete(); - } - - private void deliverCurrentMessageIfComplete() - { - // check and deliver if header says body length is zero - if (_currentMessage.allContentReceived()) - { - if(_confirmOnPublish) - { - _confirmedMessageCounter++; - } - Runnable finallyAction = null; - ContentHeaderBody contentHeader = _currentMessage.getContentHeader(); - - long bodySize = _currentMessage.getSize(); - long timestamp = contentHeader.getProperties().getTimestamp(); - - try - { - - final MessagePublishInfo messagePublishInfo = _currentMessage.getMessagePublishInfo(); - final MessageDestination destination = _currentMessage.getDestination(); - - final MessageMetaData messageMetaData = - new MessageMetaData(messagePublishInfo, - contentHeader, - getConnection().getLastReceivedTime()); - - final MessageHandle handle = _messageStore.addMessage(messageMetaData); - int bodyCount = _currentMessage.getBodyCount(); - if(bodyCount > 0) - { - long bodyLengthReceived = 0; - for(int i = 0 ; i < bodyCount ; i++) - { - ContentBody contentChunk = _currentMessage.getContentChunk(i); - handle.addContent(ByteBuffer.wrap(contentChunk.getPayload())); - bodyLengthReceived += contentChunk.getSize(); - } - } - final StoredMessage storedMessage = handle.allContentAdded(); - - final AMQMessage amqMessage = createAMQMessage(storedMessage); - MessageReference reference = amqMessage.newReference(); - try - { - - _currentMessage = null; - - if(!checkMessageUserId(contentHeader)) - { - if(_confirmOnPublish) - { - _connection.writeFrame(new AMQFrame(_channelId, new BasicNackBody(_confirmedMessageCounter, false, false))); - } - _transaction.addPostTransactionAction(new WriteReturnAction(AMQConstant.ACCESS_REFUSED, "Access Refused", amqMessage)); - } - else - { - final boolean immediate = messagePublishInfo.isImmediate(); - - final InstanceProperties instanceProperties = - new InstanceProperties() - { - @Override - public Object getProperty(final Property prop) - { - switch(prop) - { - case EXPIRATION: - return amqMessage.getExpiration(); - case IMMEDIATE: - return immediate; - case PERSISTENT: - return amqMessage.isPersistent(); - case MANDATORY: - return messagePublishInfo.isMandatory(); - case REDELIVERED: - return false; - } - return null; - } - }; - - int enqueues = destination.send(amqMessage, - amqMessage.getInitialRoutingAddress(), - instanceProperties, _transaction, - immediate ? _immediateAction : _capacityCheckAction - ); - if(enqueues == 0) - { - finallyAction = handleUnroutableMessage(amqMessage); - } - else - { - if(_confirmOnPublish) - { - BasicAckBody responseBody = _connection.getMethodRegistry() - .createBasicAckBody(_confirmedMessageCounter, false); - _connection.writeFrame(responseBody.generateFrame(_channelId)); - } - incrementUncommittedMessageSize(storedMessage); - incrementOutstandingTxnsIfNecessary(); - } - } - } - finally - { - reference.release(); - if(finallyAction != null) - { - finallyAction.run(); - } - } - - } - finally - { - _connection.registerMessageReceived(bodySize, timestamp); - _currentMessage = null; - } - } - - } - - private void incrementUncommittedMessageSize(final StoredMessage handle) - { - if (isTransactional()) - { - _uncommittedMessageSize += handle.getMetaData().getContentSize(); - if (_uncommittedMessageSize > getMaxUncommittedInMemorySize()) - { - handle.flowToDisk(); - if(!_uncommittedMessages.isEmpty() || _uncommittedMessageSize == handle.getMetaData().getContentSize()) - { - getVirtualHost().getEventLogger() - .message(_logSubject, ChannelMessages.LARGE_TRANSACTION_WARN(_uncommittedMessageSize)); - } - - if(!_uncommittedMessages.isEmpty()) - { - for (StoredMessage uncommittedHandle : _uncommittedMessages) - { - uncommittedHandle.flowToDisk(); - } - _uncommittedMessages.clear(); - } - } - else - { - _uncommittedMessages.add(handle); - } - } - } - - /** - * Either throws a {@link AMQConnectionException} or returns the message - * - * Pre-requisite: the current message is judged to have no destination queues. - * - * @throws AMQConnectionException if the message is mandatory close-on-no-route - * @see AMQProtocolEngine#isCloseWhenNoRoute() - */ - private Runnable handleUnroutableMessage(AMQMessage message) - { - boolean mandatory = message.isMandatory(); - - String exchangeName = message.getMessagePublishInfo().getExchange() == null - ? null : message.getMessagePublishInfo().getExchange().asString(); - String routingKey = message.getMessagePublishInfo().getRoutingKey() == null - ? null : message.getMessagePublishInfo().getRoutingKey().asString(); - - final String description = String.format( - "[Exchange: %s, Routing key: %s]", - exchangeName, - routingKey); - - boolean closeOnNoRoute = _connection.isCloseWhenNoRoute(); - Runnable returnVal = null; - if(_logger.isDebugEnabled()) - { - _logger.debug(String.format( - "Unroutable message %s, mandatory=%s, transactionalSession=%s, closeOnNoRoute=%s", - description, mandatory, isTransactional(), closeOnNoRoute)); - } - - if (mandatory && isTransactional() && !_confirmOnPublish && _connection.isCloseWhenNoRoute()) - { - returnVal = new Runnable() - { - @Override - public void run() - { - _connection.closeConnection(AMQConstant.NO_ROUTE, - "No route for message " + description, _channelId); - - } - }; - } - else - { - if (mandatory || message.isImmediate()) - { - if(_confirmOnPublish) - { - _connection.writeFrame(new AMQFrame(_channelId, new BasicNackBody(_confirmedMessageCounter, false, false))); - } - _transaction.addPostTransactionAction(new WriteReturnAction(AMQConstant.NO_ROUTE, - "No Route for message " - + description, - message)); - } - else - { - - getVirtualHost().getEventLogger().message(ExchangeMessages.DISCARDMSG(exchangeName, routingKey)); - } - } - return returnVal; - } - - public void publishContentBody(ContentBody contentBody) - { - if (_logger.isDebugEnabled()) - { - _logger.debug(debugIdentity() + " content body received on channel " + _channelId); - } - - try - { - long currentSize = _currentMessage.addContentBodyFrame(contentBody); - if(currentSize > _currentMessage.getSize()) - { - _connection.closeConnection(AMQConstant.FRAME_ERROR, - "More message data received than content header defined", - _channelId); - } - else - { - deliverCurrentMessageIfComplete(); - } - } - catch (RuntimeException 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; - } - } - - public long getNextDeliveryTag() - { - return ++_deliveryTag; - } - - public int getNextConsumerTag() - { - return ++_consumerTag; - } - - - public ConsumerTarget getSubscription(AMQShortString tag) - { - return _tag2SubscriptionTargetMap.get(tag); - } - - /** - * 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 sources the queues to subscribe to - * @param acks Are acks enabled for this subscriber - * @param arguments Filters to apply to this subscriber - * - * @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 org.apache.qpid.AMQException if something goes wrong - */ - public AMQShortString consumeFromSource(AMQShortString tag, Collection sources, boolean acks, - FieldTable arguments, boolean exclusive, boolean noLocal) - throws MessageSource.ExistingConsumerPreventsExclusive, - MessageSource.ExistingExclusiveConsumer, - AMQInvalidArgumentException, - MessageSource.ConsumerAccessRefused, ConsumerTagInUseException - { - if (tag == null) - { - tag = new AMQShortString("sgen_" + getNextConsumerTag()); - } - - if (_tag2SubscriptionTargetMap.containsKey(tag)) - { - throw new ConsumerTagInUseException("Consumer already exists with same tag: " + tag); - } - - ConsumerTarget_0_8 target; - EnumSet options = EnumSet.noneOf(ConsumerImpl.Option.class); - - if(arguments != null && Boolean.TRUE.equals(arguments.get(AMQPFilterTypes.NO_CONSUME.getValue()))) - { - target = ConsumerTarget_0_8.createBrowserTarget(this, tag, arguments, _noAckCreditManager); - } - else if(acks) - { - target = ConsumerTarget_0_8.createAckTarget(this, tag, arguments, _creditManager); - options.add(ConsumerImpl.Option.ACQUIRES); - options.add(ConsumerImpl.Option.SEES_REQUEUES); - } - else - { - target = ConsumerTarget_0_8.createNoAckTarget(this, tag, arguments, _noAckCreditManager); - options.add(ConsumerImpl.Option.ACQUIRES); - options.add(ConsumerImpl.Option.SEES_REQUEUES); - } - - if(exclusive) - { - options.add(ConsumerImpl.Option.EXCLUSIVE); - } - - - // 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. - - _tag2SubscriptionTargetMap.put(tag, target); - - try - { - FilterManager filterManager = FilterManagerFactory.createManager(FieldTable.convertToMap(arguments)); - if(noLocal) - { - if(filterManager == null) - { - filterManager = new FilterManager(); - } - final Object connectionReference = getConnectionReference(); - MessageFilter filter = new MessageFilter() - { - - @Override - public String getName() - { - return AMQPFilterTypes.NO_LOCAL.toString(); - } - - @Override - public boolean matches(final Filterable message) - { - return message.getConnectionReference() != connectionReference; - } - - @Override - public boolean startAtTail() - { - return false; - } - }; - filterManager.add(filter.getName(), filter); - } - - if(arguments != null && arguments.containsKey(AMQPFilterTypes.REPLAY_PERIOD.toString())) - { - Object value = arguments.get(AMQPFilterTypes.REPLAY_PERIOD.toString()); - final long period; - if(value instanceof Number) - { - period = ((Number)value).longValue(); - } - else if(value instanceof String) - { - try - { - period = Long.parseLong(value.toString()); - } - catch (NumberFormatException e) - { - throw new AMQInvalidArgumentException("Cannot parse value " + value + " as a number for filter " + AMQPFilterTypes.REPLAY_PERIOD.toString()); - } - } - else - { - throw new AMQInvalidArgumentException("Cannot parse value " + value + " as a number for filter " + AMQPFilterTypes.REPLAY_PERIOD.toString()); - } - - final long startingFrom = System.currentTimeMillis() - (1000l * period); - if(filterManager == null) - { - filterManager = new FilterManager(); - } - MessageFilter filter = new ArrivalTimeFilter(startingFrom, period==0); - filterManager.add(filter.getName(), filter); - - } - - for(MessageSource source : sources) - { - ConsumerImpl sub = - source.addConsumer(target, - filterManager, - AMQMessage.class, - AMQShortString.toString(tag), - options); - if (sub instanceof Consumer) - { - final Consumer modelConsumer = (Consumer) sub; - consumerAdded(modelConsumer); - modelConsumer.addChangeListener(_consumerClosedListener); - _consumers.add(modelConsumer); - } - } - } - catch (AccessControlException - | MessageSource.ExistingExclusiveConsumer - | MessageSource.ExistingConsumerPreventsExclusive - | AMQInvalidArgumentException - | MessageSource.ConsumerAccessRefused e) - { - _tag2SubscriptionTargetMap.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. - */ - public boolean unsubscribeConsumer(AMQShortString consumerTag) - { - - ConsumerTarget_0_8 target = _tag2SubscriptionTargetMap.remove(consumerTag); - Collection subs = target == null ? null : target.getConsumers(); - if (subs != null) - { - for(ConsumerImpl sub : subs) - { - sub.close(); - if (sub instanceof Consumer) - { - _consumers.remove(sub); - } - } - return true; - } - else - { - _logger.warn("Attempt to unsubscribe consumer with tag '" + consumerTag + "' which is not registered."); - } - return false; - } - - @Override - public void close() - { - close(null, null); - } - - public void close(AMQConstant cause, String message) - { - if(!_closing.compareAndSet(false, true)) - { - //Channel is already closing - return; - } - - LogMessage operationalLogMessage = cause == null ? - ChannelMessages.CLOSE() : - ChannelMessages.CLOSE_FORCED(cause.getCode(), message); - getVirtualHost().getEventLogger().message(_logSubject, operationalLogMessage); - - unsubscribeAllConsumers(); - setDefaultQueue(null); - for (Action task : _taskList) - { - task.performAction(this); - } - - - _transaction.rollback(); - - try - { - requeue(); - } - catch (TransportException e) - { - _logger.error("Caught TransportException whilst attempting to requeue:" + e); - } - } - - private void unsubscribeAllConsumers() - { - if (_logger.isInfoEnabled()) - { - if (!_tag2SubscriptionTargetMap.isEmpty()) - { - _logger.info("Unsubscribing all consumers on channel " + toString()); - } - else - { - _logger.info("No consumers to unsubscribe on channel " + toString()); - } - } - - for (Map.Entry me : _tag2SubscriptionTargetMap.entrySet()) - { - if (_logger.isInfoEnabled()) - { - _logger.info("Unsubscribing consumer '" + me.getKey() + "' on channel " + toString()); - } - - Collection subs = me.getValue().getConsumers(); - - if(subs != null) - { - for(ConsumerImpl sub : subs) - { - sub.close(); - } - } - } - - _tag2SubscriptionTargetMap.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 consumer The consumer that is to acknowledge this message. - */ - public void addUnacknowledgedMessage(MessageInstance entry, long deliveryTag, ConsumerImpl consumer) - { - if (_logger.isDebugEnabled()) - { - _logger.debug(debugIdentity() + " Adding unacked message(" + entry.getMessage().toString() + " DT:" + deliveryTag - + ") for " + consumer + " on " + entry.getOwningResource().getName()); - - } - - _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. - * - */ - public void requeue() - { - // we must create a new map since all the messages will get a new delivery tag when they are redelivered - Collection messagesToBeDelivered = _unacknowledgedMessageMap.cancelAllMessages(); - - if (!messagesToBeDelivered.isEmpty()) - { - if (_logger.isInfoEnabled()) - { - _logger.info("Requeuing " + messagesToBeDelivered.size() + " unacked messages. for " + toString()); - } - - } - - for (MessageInstance unacked : messagesToBeDelivered) - { - // Mark message redelivered - unacked.setRedelivered(); - - // Ensure message is released for redelivery - unacked.release(); - } - - } - - /** - * Requeue a single message - * - * @param deliveryTag The message to requeue - * - */ - public void requeue(long deliveryTag) - { - MessageInstance unacked = _unacknowledgedMessageMap.remove(deliveryTag); - - if (unacked != null) - { - // Mark message redelivered - unacked.setRedelivered(); - - // Ensure message is released for redelivery - unacked.release(); - - } - else - { - _logger.warn("Requested requeue of message:" + deliveryTag + " but no such delivery tag exists." - + _unacknowledgedMessageMap.size()); - - } - - } - - public boolean isMaxDeliveryCountEnabled(final long deliveryTag) - { - final MessageInstance queueEntry = _unacknowledgedMessageMap.get(deliveryTag); - if (queueEntry != null) - { - final int maximumDeliveryCount = queueEntry.getMaximumDeliveryCount(); - return maximumDeliveryCount > 0; - } - - return false; - } - - public boolean isDeliveredTooManyTimes(final long deliveryTag) - { - final MessageInstance queueEntry = _unacknowledgedMessageMap.get(deliveryTag); - if (queueEntry != null) - { - final int maximumDeliveryCount = queueEntry.getMaximumDeliveryCount(); - final int numDeliveries = queueEntry.getDeliveryCount(); - return maximumDeliveryCount != 0 && numDeliveries >= maximumDeliveryCount; - } - - return false; - } - - /** - * Called to resend all outstanding unacknowledged messages to this same channel. - * - */ - public void resend() - { - - - final Map msgToRequeue = new LinkedHashMap(); - final Map msgToResend = new LinkedHashMap(); - - 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 - )); - - - // 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 entry : msgToResend.entrySet()) - { - MessageInstance message = entry.getValue(); - long deliveryTag = entry.getKey(); - - //Amend the delivery counter as the client hasn't seen these messages yet. - message.decrementDeliveryCount(); - - // 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(); - - if (!message.resend()) - { - 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 entry : msgToRequeue.entrySet()) - { - MessageInstance message = entry.getValue(); - long deliveryTag = entry.getKey(); - - //Amend the delivery counter as the client hasn't seen these messages yet. - message.decrementDeliveryCount(); - - _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 - * - */ - public void acknowledgeMessage(long deliveryTag, boolean multiple) - { - Collection ackedMessages = getAckedMessages(deliveryTag, multiple); - _transaction.dequeue(ackedMessages, new MessageAcknowledgeAction(ackedMessages)); - } - - private Collection getAckedMessages(long deliveryTag, boolean multiple) - { - - return _unacknowledgedMessageMap.acknowledge(deliveryTag, multiple); - - } - - /** - * 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) - { - getVirtualHost().getEventLogger().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 deciding to start an async delivery was located with the - // Subscription. - if (wasSuspended) - { - // may need to deliver queued messages - for (ConsumerTarget_0_8 s : _tag2SubscriptionTargetMap.values()) - { - for(ConsumerImpl sub : s.getConsumers()) - { - sub.externalStateChange(); - } - } - } - - - // 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 (ConsumerTarget_0_8 s : _tag2SubscriptionTargetMap.values()) - { - try - { - s.getSendLock(); - } - finally - { - s.releaseSendLock(); - } - } - } - - - // Log Suspension only after we have confirmed all suspensions are - // stopped. - if (suspended) - { - getVirtualHost().getEventLogger().message(_logSubject, ChannelMessages.FLOW("Stopped")); - } - - } - } - - public boolean isSuspended() - { - return _suspended.get() || _closing.get() || _connection.isClosing(); - } - - - public void commit(final Runnable immediateAction, boolean async) - { - - - if(async && _transaction instanceof LocalTransaction) - { - - ((LocalTransaction)_transaction).commitAsync(new Runnable() - { - @Override - public void run() - { - try - { - immediateAction.run(); - } - finally - { - _txnCommits.incrementAndGet(); - _txnStarts.incrementAndGet(); - decrementOutstandingTxnsIfNecessary(); - } - } - }); - } - else - { - _transaction.commit(immediateAction); - - _txnCommits.incrementAndGet(); - _txnStarts.incrementAndGet(); - decrementOutstandingTxnsIfNecessary(); - } - resetUncommittedMessages(); - } - - private void resetUncommittedMessages() - { - _uncommittedMessageSize = 0l; - _uncommittedMessages.clear(); - } - - public void rollback(Runnable postRollbackTask) - { - - // stop all subscriptions - _rollingBack = true; - boolean requiresSuspend = _suspended.compareAndSet(false,true); // TODO This is probably superfluous owing to the - // message assignment suspended logic in NBC. - - // ensure all subscriptions have seen the change to the channel state - for(ConsumerTarget_0_8 sub : _tag2SubscriptionTargetMap.values()) - { - sub.getSendLock(); - sub.releaseSendLock(); - } - - try - { - _transaction.rollback(); - } - finally - { - _rollingBack = false; - - _txnRejects.incrementAndGet(); - _txnStarts.incrementAndGet(); - decrementOutstandingTxnsIfNecessary(); - resetUncommittedMessages(); - } - - postRollbackTask.run(); - - for(MessageInstance entry : _resendList) - { - ConsumerImpl sub = entry.getDeliveredConsumer(); - if(sub == null || sub.isClosed()) - { - entry.release(); - } - else - { - entry.resend(); - } - } - _resendList.clear(); - - if(requiresSuspend) - { - _suspended.set(false); - for(ConsumerTarget_0_8 target : _tag2SubscriptionTargetMap.values()) - { - for(ConsumerImpl sub : target.getConsumers()) - { - sub.externalStateChange(); - } - } - - } - } - - public String toString() - { - return "("+ _suspended.get() + ", " + _closing.get() + ", " + _connection.isClosing() + ") "+"["+ _connection.toString()+":"+_channelId+"]"; - } - - public boolean isClosing() - { - return _closing.get(); - } - - public AMQProtocolEngine getConnection() - { - return _connection; - } - - public FlowCreditManager getCreditManager() - { - return _creditManager; - } - - public void setCredit(final long prefetchSize, final int prefetchCount) - { - getVirtualHost().getEventLogger().message(ChannelMessages.PREFETCH_SIZE(prefetchSize, prefetchCount)); - _creditManager.setCreditLimits(prefetchSize, prefetchCount); - } - - public MessageStore getMessageStore() - { - return _messageStore; - } - - public ClientDeliveryMethod getClientDeliveryMethod() - { - return _clientDeliveryMethod; - } - - private final RecordDeliveryMethod _recordDeliveryMethod = new RecordDeliveryMethod() - { - - public void recordMessageDelivery(final ConsumerImpl sub, final MessageInstance entry, final long deliveryTag) - { - addUnacknowledgedMessage(entry, deliveryTag, sub); - } - }; - - public RecordDeliveryMethod getRecordDeliveryMethod() - { - return _recordDeliveryMethod; - } - - - private AMQMessage createAMQMessage(StoredMessage handle) - { - - AMQMessage message = new AMQMessage(handle, _connection.getReference()); - - return message; - } - - private boolean checkMessageUserId(ContentHeaderBody header) - { - AMQShortString userID = header.getProperties().getUserId(); - return (!_messageAuthorizationRequired || _connection.getAuthorizedPrincipal().getName().equals(userID == null? "" : userID.toString())); - - } - - @Override - public UUID getId() - { - return _id; - } - - @Override - public AMQProtocolEngine getConnectionModel() - { - return _connection; - } - - public String getClientID() - { - return String.valueOf(_connection.getContextKey()); - } - - public LogSubject getLogSubject() - { - return _logSubject; - } - - @Override - public int compareTo(AMQSessionModel o) - { - return getId().compareTo(o.getId()); - } - - @Override - public void addDeleteTask(final Action task) - { - _taskList.add(task); - } - - @Override - public void removeDeleteTask(final Action task) - { - _taskList.remove(task); - } - - public Subject getSubject() - { - return _subject; - } - - public boolean hasCurrentMessage() - { - return _currentMessage != null; - } - - public long getMaxUncommittedInMemorySize() - { - return _maxUncommittedInMemorySize; - } - - private class GetDeliveryMethod implements ClientDeliveryMethod - { - - private final FlowCreditManager _singleMessageCredit; - private final AMQQueue _queue; - private boolean _deliveredMessage; - - public GetDeliveryMethod(final FlowCreditManager singleMessageCredit, - final AMQQueue queue) - { - _singleMessageCredit = singleMessageCredit; - _queue = queue; - } - - @Override - public long deliverToClient(final ConsumerImpl sub, final ServerMessage message, - final InstanceProperties props, final long deliveryTag) - { - _singleMessageCredit.useCreditForMessage(message.getSize()); - long size = _connection.getProtocolOutputConverter().writeGetOk(message, - props, - AMQChannel.this.getChannelId(), - deliveryTag, - _queue.getQueueDepthMessages()); - - _deliveredMessage = true; - return size; - } - - public boolean hasDeliveredMessage() - { - return _deliveredMessage; - } - } - - - private class ImmediateAction implements Action - { - - public ImmediateAction() - { - } - - public void performAction(MessageInstance entry) - { - TransactionLogResource queue = entry.getOwningResource(); - - if (!entry.getDeliveredToConsumer() && entry.acquire()) - { - - ServerTransaction txn = new LocalTransaction(_messageStore); - final AMQMessage message = (AMQMessage) entry.getMessage(); - MessageReference ref = message.newReference(); - try - { - entry.delete(); - txn.dequeue(entry.getEnqueueRecord(), - new ServerTransaction.Action() - { - @Override - public void postCommit() - { - final ProtocolOutputConverter outputConverter = - _connection.getProtocolOutputConverter(); - - outputConverter.writeReturn(message.getMessagePublishInfo(), - message.getContentHeaderBody(), - message, - _channelId, - AMQConstant.NO_CONSUMERS.getCode(), - IMMEDIATE_DELIVERY_REPLY_TEXT); - - } - - @Override - public void onRollback() - { - - } - } - ); - txn.commit(); - } - finally - { - ref.release(); - } - - - } - else - { - if(queue instanceof CapacityChecker) - { - ((CapacityChecker)queue).checkCapacity(AMQChannel.this); - } - } - - } - } - - private final class CapacityCheckAction implements Action - { - @Override - public void performAction(final MessageInstance entry) - { - TransactionLogResource queue = entry.getOwningResource(); - if(queue instanceof CapacityChecker) - { - ((CapacityChecker)queue).checkCapacity(AMQChannel.this); - } - } - } - - private class MessageAcknowledgeAction implements ServerTransaction.Action - { - private final Collection _ackedMessages; - - public MessageAcknowledgeAction(Collection ackedMessages) - { - _ackedMessages = ackedMessages; - } - - public void postCommit() - { - try - { - for(MessageInstance entry : _ackedMessages) - { - entry.delete(); - } - } - finally - { - _ackedMessages.clear(); - } - - } - - public void onRollback() - { - // explicit rollbacks resend the message after the rollback-ok is sent - if(_rollingBack) - { - for(MessageInstance entry : _ackedMessages) - { - entry.unlockAcquisition(); - } - _resendList.addAll(_ackedMessages); - } - else - { - try - { - for(MessageInstance entry : _ackedMessages) - { - entry.release(); - } - } - finally - { - _ackedMessages.clear(); - } - } - - } - } - - private class WriteReturnAction implements ServerTransaction.Action - { - private final AMQConstant _errorCode; - private final String _description; - private final MessageReference _reference; - - public WriteReturnAction(AMQConstant errorCode, - String description, - AMQMessage message) - { - _errorCode = errorCode; - _description = description; - _reference = message.newReference(); - } - - public void postCommit() - { - AMQMessage message = _reference.getMessage(); - _connection.getProtocolOutputConverter().writeReturn(message.getMessagePublishInfo(), - message.getContentHeaderBody(), - message, - _channelId, - _errorCode.getCode(), - AMQShortString.validValueOf(_description)); - _reference.release(); - } - - public void onRollback() - { - _reference.release(); - } - } - - public synchronized void block() - { - if(_blockingEntities.add(this)) - { - - if(_blocking.compareAndSet(false,true)) - { - getVirtualHost().getEventLogger().message(_logSubject, - ChannelMessages.FLOW_ENFORCED("** All Queues **")); - - - getConnection().notifyWork(); - } - } - } - - public synchronized void unblock() - { - if(_blockingEntities.remove(this)) - { - if(_blockingEntities.isEmpty() && _blocking.compareAndSet(true,false)) - { - getVirtualHost().getEventLogger().message(_logSubject, ChannelMessages.FLOW_REMOVED()); - getConnection().notifyWork(); - } - } - } - - - public synchronized void block(AMQQueue queue) - { - if(_blockingEntities.add(queue)) - { - - if(_blocking.compareAndSet(false,true)) - { - getVirtualHost().getEventLogger().message(_logSubject, ChannelMessages.FLOW_ENFORCED(queue.getName())); - getConnection().notifyWork(); - - } - } - } - - public synchronized void unblock(AMQQueue queue) - { - if(_blockingEntities.remove(queue)) - { - if(_blockingEntities.isEmpty() && _blocking.compareAndSet(true,false) && !isClosing()) - { - getVirtualHost().getEventLogger().message(_logSubject, ChannelMessages.FLOW_REMOVED()); - getConnection().notifyWork(); - } - } - } - - @Override - public void transportStateChanged() - { - _creditManager.restoreCredit(0, 0); - _noAckCreditManager.restoreCredit(0, 0); - } - - @Override - public Object getConnectionReference() - { - return getConnection().getReference(); - } - - public int getUnacknowledgedMessageCount() - { - return getUnacknowledgedMessageMap().size(); - } - - private void flow(boolean flow) - { - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createChannelFlowBody(flow); - _connection.writeFrame(responseBody.generateFrame(_channelId)); - } - - @Override - public boolean getBlocking() - { - return _blocking.get(); - } - - public VirtualHostImpl getVirtualHost() - { - return getConnection().getVirtualHost(); - } - - public void checkTransactionStatus(long openWarn, long openClose, long idleWarn, long idleClose) - { - _transactionTimeoutHelper.checkIdleOrOpenTimes(_transaction, openWarn, openClose, idleWarn, idleClose); - } - - /** - * Typically called from the HouseKeepingThread instead of the main receiver thread, - * therefore uses a lock to close the connection in a thread-safe manner. - */ - private void closeConnection(String reason) throws AMQException - { - _connection.closeAsync(AMQConstant.RESOURCE_ERROR, reason); - } - - public void deadLetter(long deliveryTag) - { - final UnacknowledgedMessageMap unackedMap = getUnacknowledgedMessageMap(); - final MessageInstance rejectedQueueEntry = unackedMap.remove(deliveryTag); - - if (rejectedQueueEntry == null) - { - _logger.warn("No message found, unable to DLQ delivery tag: " + deliveryTag); - } - else - { - final ServerMessage msg = rejectedQueueEntry.getMessage(); - - - int requeues = rejectedQueueEntry.routeToAlternate(new Action() - { - @Override - public void performAction(final MessageInstance requeueEntry) - { - getVirtualHost().getEventLogger().message(_logSubject, - ChannelMessages.DEADLETTERMSG(msg.getMessageNumber(), - requeueEntry.getOwningResource() - .getName())); - } - }, null); - - if(requeues == 0) - { - - final TransactionLogResource owningResource = rejectedQueueEntry.getOwningResource(); - if(owningResource instanceof AMQQueue) - { - final AMQQueue queue = (AMQQueue) owningResource; - - final Exchange altExchange = queue.getAlternateExchange(); - - if (altExchange == null) - { - _logger.debug("No alternate exchange configured for queue, must discard the message as unable to DLQ: delivery tag: " + deliveryTag); - getVirtualHost().getEventLogger().message(_logSubject, - ChannelMessages.DISCARDMSG_NOALTEXCH(msg.getMessageNumber(), - queue.getName(), - msg.getInitialRoutingAddress())); - - } - else - { - _logger.debug( - "Routing process provided no queues to enqueue the message on, must discard message as unable to DLQ: delivery tag: " - + deliveryTag); - getVirtualHost().getEventLogger().message(_logSubject, - ChannelMessages.DISCARDMSG_NOROUTE(msg.getMessageNumber(), - altExchange.getName())); - } - } - } - - } - } - - public void recordFuture(final FutureResult future, final ServerTransaction.Action action) - { - _unfinishedCommandsQueue.add(new AsyncCommand(future, action)); - } - - public void sync() - { - if(_logger.isDebugEnabled()) - { - _logger.debug("sync() called on channel " + debugIdentity()); - } - - AsyncCommand cmd; - while((cmd = _unfinishedCommandsQueue.poll()) != null) - { - cmd.awaitReadyForCompletion(); - cmd.complete(); - } - if(_transaction instanceof LocalTransaction) - { - ((LocalTransaction)_transaction).sync(); - } - } - - private static class AsyncCommand - { - private final FutureResult _future; - private ServerTransaction.Action _action; - - public AsyncCommand(final FutureResult future, final ServerTransaction.Action action) - { - _future = future; - _action = action; - } - - void awaitReadyForCompletion() - { - _future.waitForCompletion(); - } - - void complete() - { - if(!_future.isComplete()) - { - _future.waitForCompletion(); - } - _action.postCommit(); - _action = null; - } - } - - @Override - public int getConsumerCount() - { - return _tag2SubscriptionTargetMap.size(); - } - - @Override - public Collection> getConsumers() - { - return Collections.unmodifiableCollection(_consumers); - } - - private class ConsumerClosedListener implements ConfigurationChangeListener - { - @Override - public void stateChanged(final ConfiguredObject object, final State oldState, final State newState) - { - if(newState == State.DELETED) - { - consumerRemoved((Consumer)object); - } - } - - @Override - public void childAdded(final ConfiguredObject object, final ConfiguredObject child) - { - - } - - @Override - public void childRemoved(final ConfiguredObject object, final ConfiguredObject child) - { - - } - - @Override - public void attributeSet(final ConfiguredObject object, - final String attributeName, - final Object oldAttributeValue, - final Object newAttributeValue) - { - - } - } - - private void consumerAdded(final Consumer consumer) - { - for(ConsumerListener l : _consumerListeners) - { - l.consumerAdded(consumer); - } - } - - private void consumerRemoved(final Consumer consumer) - { - for(ConsumerListener l : _consumerListeners) - { - l.consumerRemoved(consumer); - } - } - - @Override - public void addConsumerListener(ConsumerListener listener) - { - _consumerListeners.add(listener); - } - - @Override - public void removeConsumerListener(ConsumerListener listener) - { - _consumerListeners.remove(listener); - } - - @Override - public void setModelObject(final Session session) - { - _modelObject = session; - } - - @Override - public Session getModelObject() - { - return _modelObject; - } - - @Override - public long getTransactionStartTime() - { - ServerTransaction serverTransaction = _transaction; - if (serverTransaction.isTransactional()) - { - return serverTransaction.getTransactionStartTime(); - } - else - { - return 0L; - } - } - - @Override - public long getTransactionUpdateTime() - { - ServerTransaction serverTransaction = _transaction; - if (serverTransaction.isTransactional()) - { - return serverTransaction.getTransactionUpdateTime(); - } - else - { - return 0L; - } - } - - @Override - public void receiveAccessRequest(final AMQShortString realm, - final boolean exclusive, - final boolean passive, - final boolean active, final boolean write, final boolean read) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] AccessRequest[" +" realm: " + realm + - " exclusive: " + exclusive + - " passive: " + passive + - " active: " + active + - " write: " + write + " read: " + read + " ]"); - } - - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - - if (ProtocolVersion.v0_91.equals(_connection.getProtocolVersion())) - { - _connection.closeConnection(AMQConstant.COMMAND_INVALID, - "AccessRequest not present in AMQP versions other than 0-8, 0-9", - _channelId); - } - else - { - // We don't implement access control class, but to keep clients happy that expect it - // always use the "0" ticket. - AccessRequestOkBody response = methodRegistry.createAccessRequestOkBody(0); - sync(); - _connection.writeFrame(response.generateFrame(_channelId)); - } - } - - @Override - public void receiveBasicAck(final long deliveryTag, final boolean multiple) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] BasicAck[" +" deliveryTag: " + deliveryTag + " multiple: " + multiple + " ]"); - } - - acknowledgeMessage(deliveryTag, multiple); - } - - @Override - public void receiveBasicCancel(final AMQShortString consumerTag, final boolean nowait) - { - - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] BasicCancel[" +" consumerTag: " + consumerTag + " noWait: " + nowait + " ]"); - } - - unsubscribeConsumer(consumerTag); - if (!nowait) - { - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - BasicCancelOkBody cancelOkBody = methodRegistry.createBasicCancelOkBody(consumerTag); - sync(); - _connection.writeFrame(cancelOkBody.generateFrame(_channelId)); - } - } - - @Override - public void receiveBasicConsume(final AMQShortString queue, - final AMQShortString consumerTag, - final boolean noLocal, - final boolean noAck, - final boolean exclusive, final boolean nowait, final FieldTable arguments) - { - - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] BasicConsume[" +" queue: " + queue + - " consumerTag: " + consumerTag + - " noLocal: " + noLocal + - " noAck: " + noAck + - " exclusive: " + exclusive + " nowait: " + nowait + " arguments: " + arguments + " ]"); - } - - AMQShortString consumerTag1 = consumerTag; - VirtualHostImpl vHost = _connection.getVirtualHost(); - sync(); - String queueName = queue == null ? null : queue.asString(); - - MessageSource queue1 = queueName == null ? getDefaultQueue() : vHost.getQueue(queueName); - final Collection sources = new HashSet<>(); - if (queue1 != null) - { - sources.add(queue1); - } - else if (vHost.getContextValue(Boolean.class, "qpid.enableMultiQueueConsumers") - && arguments != null - && arguments.get("x-multiqueue") instanceof Collection) - { - for (Object object : (Collection) arguments.get("x-multiqueue")) - { - String sourceName = String.valueOf(object); - sourceName = sourceName.trim(); - if (sourceName.length() != 0) - { - MessageSource source = vHost.getMessageSource(sourceName); - if (source == null) - { - sources.clear(); - break; - } - else - { - sources.add(source); - } - } - } - queueName = arguments.get("x-multiqueue").toString(); - } - - if (sources.isEmpty()) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("No queue for '" + queueName + "'"); - } - if (queueName != null) - { - closeChannel(AMQConstant.NOT_FOUND, "No such queue, '" + queueName + "'"); - } - else - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, - "No queue name provided, no default queue defined.", _channelId); - } - } - else - { - try - { - consumerTag1 = consumeFromSource(consumerTag1, - sources, - !noAck, - arguments, - exclusive, - noLocal); - if (!nowait) - { - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createBasicConsumeOkBody(consumerTag1); - _connection.writeFrame(responseBody.generateFrame(_channelId)); - - } - } - catch (ConsumerTagInUseException cte) - { - - _connection.closeConnection(AMQConstant.NOT_ALLOWED, - "Non-unique consumer tag, '" + consumerTag1 - + "'", _channelId); - } - catch (AMQInvalidArgumentException ise) - { - _connection.closeConnection(AMQConstant.ARGUMENT_INVALID, ise.getMessage(), _channelId); - - - } - catch (AMQQueue.ExistingExclusiveConsumer e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, - "Cannot subscribe to queue '" - + queue1.getName() - + "' as it already has an existing exclusive consumer", _channelId); - - } - catch (AMQQueue.ExistingConsumerPreventsExclusive e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, - "Cannot subscribe to queue '" - + queue1.getName() - + "' exclusively as it already has a consumer", _channelId); - - } - catch (AccessControlException e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, "Cannot subscribe to queue '" - + queue1.getName() - + "' permission denied", _channelId); - - } - catch (MessageSource.ConsumerAccessRefused consumerAccessRefused) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, - "Cannot subscribe to queue '" - + queue1.getName() - + "' as it already has an incompatible exclusivity policy", _channelId); - - } - - } - } - - @Override - public void receiveBasicGet(final AMQShortString queueName, final boolean noAck) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] BasicGet[" +" queue: " + queueName + " noAck: " + noAck + " ]"); - } - - VirtualHostImpl vHost = _connection.getVirtualHost(); - sync(); - AMQQueue queue = queueName == null ? getDefaultQueue() : vHost.getQueue(queueName.toString()); - if (queue == null) - { - _logger.info("No queue for '" + queueName + "'"); - if (queueName != null) - { - _connection.closeConnection(AMQConstant.NOT_FOUND, "No such queue, '" + queueName + "'", _channelId); - - } - else - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, - "No queue name provided, no default queue defined.", _channelId); - - } - } - else - { - - try - { - if (!performGet(queue, !noAck)) - { - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - - BasicGetEmptyBody responseBody = methodRegistry.createBasicGetEmptyBody(null); - - _connection.writeFrame(responseBody.generateFrame(_channelId)); - } - } - catch (AccessControlException e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, e.getMessage(), _channelId); - } - catch (MessageSource.ExistingExclusiveConsumer e) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, "Queue has an exclusive consumer", _channelId); - } - catch (MessageSource.ExistingConsumerPreventsExclusive e) - { - _connection.closeConnection(AMQConstant.INTERNAL_ERROR, - "The GET request has been evaluated as an exclusive consumer, " + - "this is likely due to a programming error in the Qpid broker", _channelId); - } - catch (MessageSource.ConsumerAccessRefused consumerAccessRefused) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, - "Queue has an incompatible exclusivity policy", _channelId); - } - } - } - - @Override - public void receiveBasicPublish(final AMQShortString exchangeName, - final AMQShortString routingKey, - final boolean mandatory, - final boolean immediate) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] BasicPublish[" +" exchange: " + exchangeName + - " routingKey: " + routingKey + - " mandatory: " + mandatory + - " immediate: " + immediate + " ]"); - } - - - - VirtualHostImpl vHost = _connection.getVirtualHost(); - - if(blockingTimeoutExceeded()) - { - getVirtualHost().getEventLogger().message(ChannelMessages.FLOW_CONTROL_IGNORED()); - closeChannel(AMQConstant.MESSAGE_TOO_LARGE, - "Channel flow control was requested, but not enforced by sender"); - } - else - { - MessageDestination destination; - - if (isDefaultExchange(exchangeName)) - { - destination = vHost.getDefaultDestination(); - } - else - { - destination = vHost.getMessageDestination(exchangeName.toString()); - } - - // if the exchange does not exist we raise a channel exception - if (destination == null) - { - closeChannel(AMQConstant.NOT_FOUND, "Unknown exchange name: '" + exchangeName + "'"); - } - else - { - - MessagePublishInfo info = new MessagePublishInfo(exchangeName, - immediate, - mandatory, - routingKey); - - try - { - setPublishFrame(info, destination); - } - catch (AccessControlException e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, e.getMessage(), getChannelId()); - - } - } - } - } - - private boolean blockingTimeoutExceeded() - { - - return _wireBlockingState && (System.currentTimeMillis() - _blockTime) > _blockingTimeout; - } - - @Override - public void receiveBasicQos(final long prefetchSize, final int prefetchCount, final boolean global) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] BasicQos[" +" prefetchSize: " + prefetchSize + " prefetchCount: " + prefetchCount + " global: " + global + " ]"); - } - - sync(); - setCredit(prefetchSize, prefetchCount); - - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createBasicQosOkBody(); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - - } - - @Override - public void receiveBasicRecover(final boolean requeue, final boolean sync) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] BasicRecover[" + " requeue: " + requeue + " sync: " + sync + " ]"); - } - - resend(); - - if (sync) - { - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody recoverOk = methodRegistry.createBasicRecoverSyncOkBody(); - sync(); - _connection.writeFrame(recoverOk.generateFrame(getChannelId())); - - } - - } - - @Override - public void receiveBasicReject(final long deliveryTag, final boolean requeue) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] BasicReject[" +" deliveryTag: " + deliveryTag + " requeue: " + requeue + " ]"); - } - - MessageInstance message = getUnacknowledgedMessageMap().get(deliveryTag); - - if (message == null) - { - _logger.warn("Dropping reject request as message is null for tag:" + deliveryTag); - } - else - { - - if (message.getMessage() == null) - { - _logger.warn("Message has already been purged, unable to Reject."); - } - else - { - - if (_logger.isDebugEnabled()) - { - _logger.debug("Rejecting: DT:" + deliveryTag - + "-" + message.getMessage() + - ": Requeue:" + requeue - + - " on channel:" + debugIdentity()); - } - - if (requeue) - { - message.decrementDeliveryCount(); - - requeue(deliveryTag); - } - else - { - // Since the Java client abuses the reject flag for requeing after rollback, we won't set reject here - // as it would prevent redelivery - // message.reject(); - - final boolean maxDeliveryCountEnabled = isMaxDeliveryCountEnabled(deliveryTag); - _logger.debug("maxDeliveryCountEnabled: " - + maxDeliveryCountEnabled - + " deliveryTag " - + deliveryTag); - if (maxDeliveryCountEnabled) - { - final boolean deliveredTooManyTimes = isDeliveredTooManyTimes(deliveryTag); - _logger.debug("deliveredTooManyTimes: " - + deliveredTooManyTimes - + " deliveryTag " - + deliveryTag); - if (deliveredTooManyTimes) - { - deadLetter(deliveryTag); - } - else - { - //this requeue represents a message rejected because of a recover/rollback that we - //are not ready to DLQ. We rely on the reject command to resend from the unacked map - //and therefore need to increment the delivery counter so we cancel out the effect - //of the AMQChannel#resend() decrement. - message.incrementDeliveryCount(); - } - } - else - { - requeue(deliveryTag); - } - } - } - } - } - - @Override - public void receiveChannelClose(final int replyCode, - final AMQShortString replyText, - final int classId, - final int methodId) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] ChannelClose[" +" replyCode: " + replyCode + " replyText: " + replyText + " classId: " + classId + " methodId: " + methodId + " ]"); - } - - - sync(); - _connection.closeChannel(this); - - _connection.writeFrame(new AMQFrame(getChannelId(), - _connection.getMethodRegistry().createChannelCloseOkBody())); - } - - @Override - public void receiveChannelCloseOk() - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] ChannelCloseOk"); - } - - _connection.closeChannelOk(getChannelId()); - } - - @Override - public void receiveMessageContent(final byte[] data) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] MessageContent[" +" data: " + hex(data,_connection.getBinaryDataLimit()) + " ] "); - } - - if(hasCurrentMessage()) - { - publishContentBody(new ContentBody(data)); - } - else - { - _connection.closeConnection(AMQConstant.COMMAND_INVALID, - "Attempt to send a content header without first sending a publish frame", - _channelId); - } - } - - @Override - public void receiveMessageHeader(final BasicContentHeaderProperties properties, final long bodySize) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] MessageHeader[ properties: {" + properties + "} bodySize: " + bodySize + " ]"); - } - - if(hasCurrentMessage()) - { - if(bodySize > _connection.getMaxMessageSize()) - { - closeChannel(AMQConstant.MESSAGE_TOO_LARGE, - "Message size of " + bodySize + " greater than allowed maximum of " + _connection.getMaxMessageSize()); - } - publishContentHeader(new ContentHeaderBody(properties, bodySize)); - } - else - { - _connection.closeConnection(AMQConstant.COMMAND_INVALID, - "Attempt to send a content header without first sending a publish frame", - _channelId); - } - } - - @Override - public boolean ignoreAllButCloseOk() - { - return _connection.ignoreAllButCloseOk() || _connection.channelAwaitingClosure(_channelId); - } - - @Override - public void receiveBasicNack(final long deliveryTag, final boolean multiple, final boolean requeue) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] BasicNack[" +" deliveryTag: " + deliveryTag + " multiple: " + multiple + " requeue: " + requeue + " ]"); - } - - Map nackedMessageMap = new LinkedHashMap<>(); - _unacknowledgedMessageMap.collect(deliveryTag, multiple, nackedMessageMap); - - for(MessageInstance message : nackedMessageMap.values()) - { - - if (message == null) - { - _logger.warn("Ignoring nack request as message is null for tag:" + deliveryTag); - } - else - { - - if (message.getMessage() == null) - { - _logger.warn("Message has already been purged, unable to nack."); - } - else - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Nack-ing: DT:" + deliveryTag - + "-" + message.getMessage() + - ": Requeue:" + requeue - + - " on channel:" + debugIdentity()); - } - - if (requeue) - { - message.decrementDeliveryCount(); - - requeue(deliveryTag); - } - else - { - message.reject(); - - final boolean maxDeliveryCountEnabled = isMaxDeliveryCountEnabled(deliveryTag); - _logger.debug("maxDeliveryCountEnabled: " - + maxDeliveryCountEnabled - + " deliveryTag " - + deliveryTag); - if (maxDeliveryCountEnabled) - { - final boolean deliveredTooManyTimes = isDeliveredTooManyTimes(deliveryTag); - _logger.debug("deliveredTooManyTimes: " - + deliveredTooManyTimes - + " deliveryTag " - + deliveryTag); - if (deliveredTooManyTimes) - { - deadLetter(deliveryTag); - } - else - { - message.incrementDeliveryCount(); - } - } - else - { - requeue(deliveryTag); - } - } - } - } - - } - - } - - @Override - public void receiveChannelFlow(final boolean active) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] ChannelFlow[" +" active: " + active + " ]"); - } - - - sync(); - setSuspended(!active); - - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createChannelFlowOkBody(active); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - - } - - @Override - public void receiveChannelFlowOk(final boolean active) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] ChannelFlowOk[" +" active: " + active + " ]"); - } - - // TODO - should we do anything here? - } - - @Override - public void receiveExchangeBound(final AMQShortString exchangeName, - final AMQShortString routingKey, - final AMQShortString queueName) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] ExchangeBound[" +" exchange: " + exchangeName + " routingKey: " + - routingKey + " queue: " + queueName + " ]"); - } - - VirtualHostImpl virtualHost = _connection.getVirtualHost(); - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - - sync(); - - int replyCode; - String replyText; - - if (isDefaultExchange(exchangeName)) - { - if (routingKey == null) - { - if (queueName == null) - { - replyCode = virtualHost.getQueues().isEmpty() - ? ExchangeBoundOkBody.NO_BINDINGS - : ExchangeBoundOkBody.OK; - replyText = null; - - } - else - { - AMQQueue queue = virtualHost.getQueue(queueName.toString()); - if (queue == null) - { - replyCode = ExchangeBoundOkBody.QUEUE_NOT_FOUND; - replyText = "Queue '" + queueName + "' not found"; - } - else - { - replyCode = ExchangeBoundOkBody.OK; - replyText = null; - } - } - } - else - { - if (queueName == null) - { - replyCode = virtualHost.getQueue(routingKey.toString()) == null - ? ExchangeBoundOkBody.NO_QUEUE_BOUND_WITH_RK - : ExchangeBoundOkBody.OK; - replyText = null; - } - else - { - AMQQueue queue = virtualHost.getQueue(queueName.toString()); - if (queue == null) - { - - replyCode = ExchangeBoundOkBody.QUEUE_NOT_FOUND; - replyText = "Queue '" + queueName + "' not found"; - } - else - { - replyCode = queueName.equals(routingKey) - ? ExchangeBoundOkBody.OK - : ExchangeBoundOkBody.SPECIFIC_QUEUE_NOT_BOUND_WITH_RK; - replyText = null; - } - } - } - } - else - { - ExchangeImpl exchange = virtualHost.getExchange(exchangeName.toString()); - if (exchange == null) - { - - replyCode = ExchangeBoundOkBody.EXCHANGE_NOT_FOUND; - replyText = "Exchange '" + exchangeName + "' not found"; - } - else if (routingKey == null) - { - if (queueName == null) - { - if (exchange.hasBindings()) - { - replyCode = ExchangeBoundOkBody.OK; - replyText = null; - } - else - { - replyCode = ExchangeBoundOkBody.NO_BINDINGS; - replyText = null; - } - } - else - { - - AMQQueue queue = virtualHost.getQueue(queueName.toString()); - if (queue == null) - { - replyCode = ExchangeBoundOkBody.QUEUE_NOT_FOUND; - replyText = "Queue '" + queueName + "' not found"; - } - else - { - if (exchange.isBound(queue)) - { - replyCode = ExchangeBoundOkBody.OK; - replyText = null; - } - else - { - replyCode = ExchangeBoundOkBody.QUEUE_NOT_BOUND; - replyText = "Queue '" - + queueName - + "' not bound to exchange '" - + exchangeName - + "'"; - } - } - } - } - else if (queueName != null) - { - AMQQueue queue = virtualHost.getQueue(queueName.toString()); - if (queue == null) - { - replyCode = ExchangeBoundOkBody.QUEUE_NOT_FOUND; - replyText = "Queue '" + queueName + "' not found"; - } - else - { - String bindingKey = routingKey == null ? null : routingKey.asString(); - if (exchange.isBound(bindingKey, queue)) - { - - replyCode = ExchangeBoundOkBody.OK; - replyText = null; - } - else - { - replyCode = ExchangeBoundOkBody.SPECIFIC_QUEUE_NOT_BOUND_WITH_RK; - replyText = "Queue '" + queueName + "' not bound with routing key '" + - routingKey + "' to exchange '" + exchangeName + "'"; - - } - } - } - else - { - if (exchange.isBound(routingKey == null ? "" : routingKey.asString())) - { - - replyCode = ExchangeBoundOkBody.OK; - replyText = null; - } - else - { - replyCode = ExchangeBoundOkBody.NO_QUEUE_BOUND_WITH_RK; - replyText = - "No queue bound with routing key '" + routingKey + "' to exchange '" + exchangeName + "'"; - } - } - } - - ExchangeBoundOkBody exchangeBoundOkBody = - methodRegistry.createExchangeBoundOkBody(replyCode, AMQShortString.validValueOf(replyText)); - - _connection.writeFrame(exchangeBoundOkBody.generateFrame(getChannelId())); - - } - - @Override - public void receiveExchangeDeclare(final AMQShortString exchangeName, - final AMQShortString type, - final boolean passive, - final boolean durable, - final boolean autoDelete, - final boolean internal, - final boolean nowait, - final FieldTable arguments) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] ExchangeDeclare[" +" exchange: " + exchangeName + - " type: " + type + - " passive: " + passive + - " durable: " + durable + - " autoDelete: " + autoDelete + - " internal: " + internal + " nowait: " + nowait + " arguments: " + arguments + " ]"); - } - - ExchangeImpl exchange; - VirtualHostImpl virtualHost = _connection.getVirtualHost(); - if (isDefaultExchange(exchangeName)) - { - if (!new AMQShortString(ExchangeDefaults.DIRECT_EXCHANGE_CLASS).equals(type)) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, "Attempt to redeclare default exchange: " - + " of type " - + ExchangeDefaults.DIRECT_EXCHANGE_CLASS - + " to " + type + ".", getChannelId()); - } - else if (!nowait) - { - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createExchangeDeclareOkBody(); - sync(); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - } - - } - else - { - if (passive) - { - exchange = virtualHost.getExchange(exchangeName.toString()); - if (exchange == null) - { - closeChannel(AMQConstant.NOT_FOUND, "Unknown exchange: '" + exchangeName + "'"); - } - else if (!(type == null || type.length() == 0) && !exchange.getType().equals(type.asString())) - { - - _connection.closeConnection(AMQConstant.NOT_ALLOWED, "Attempt to redeclare exchange: '" - + exchangeName - + "' of type " - + exchange.getType() - + " to " - + type - + ".", getChannelId()); - } - else if (!nowait) - { - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createExchangeDeclareOkBody(); - sync(); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - } - - } - else - { - try - { - String name = exchangeName == null ? null : exchangeName.intern().toString(); - String typeString = type == null ? null : type.intern().toString(); - - Map attributes = new HashMap(); - if (arguments != null) - { - attributes.putAll(FieldTable.convertToMap(arguments)); - } - attributes.put(Exchange.NAME, name); - attributes.put(Exchange.TYPE, typeString); - attributes.put(Exchange.DURABLE, durable); - attributes.put(Exchange.LIFETIME_POLICY, - autoDelete ? LifetimePolicy.DELETE_ON_NO_LINKS : LifetimePolicy.PERMANENT); - if (!attributes.containsKey(Exchange.ALTERNATE_EXCHANGE)) - { - attributes.put(Exchange.ALTERNATE_EXCHANGE, null); - } - exchange = virtualHost.createExchange(attributes); - - if (!nowait) - { - sync(); - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createExchangeDeclareOkBody(); - _connection.writeFrame(responseBody.generateFrame( - getChannelId())); - } - - } - catch (ReservedExchangeNameException e) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, - "Attempt to declare exchange: '" + exchangeName + - "' which begins with reserved prefix.", getChannelId()); - - - } - catch (ExchangeExistsException e) - { - exchange = e.getExistingExchange(); - if (!new AMQShortString(exchange.getType()).equals(type)) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, "Attempt to redeclare exchange: '" - + exchangeName + "' of type " - + exchange.getType() - + " to " + type + ".", getChannelId()); - - } - else - { - if (!nowait) - { - sync(); - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createExchangeDeclareOkBody(); - _connection.writeFrame(responseBody.generateFrame( - getChannelId())); - } - } - } - catch (NoFactoryForTypeException e) - { - _connection.closeConnection(AMQConstant.COMMAND_INVALID, "Unknown exchange type '" - + e.getType() - + "' for exchange '" - + exchangeName - + "'", getChannelId()); - - } - catch (AccessControlException e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, e.getMessage(), getChannelId()); - - } - catch (UnknownConfiguredObjectException e) - { - // note - since 0-8/9/9-1 can't set the alt. exchange this exception should never occur - final String message = "Unknown alternate exchange " - + (e.getName() != null - ? "name: '" + e.getName() + "'" - : "id: " + e.getId()); - _connection.closeConnection(AMQConstant.NOT_FOUND, message, getChannelId()); - - } - catch (IllegalArgumentException e) - { - _connection.closeConnection(AMQConstant.COMMAND_INVALID, "Error creating exchange '" - + exchangeName - + "': " - + e.getMessage(), getChannelId()); - - } - } - } - - } - - @Override - public void receiveExchangeDelete(final AMQShortString exchangeStr, final boolean ifUnused, final boolean nowait) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] ExchangeDelete[" +" exchange: " + exchangeStr + " ifUnused: " + ifUnused + " nowait: " + nowait + " ]"); - } - - - VirtualHostImpl virtualHost = _connection.getVirtualHost(); - sync(); - try - { - - if (isDefaultExchange(exchangeStr)) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, - "Default Exchange cannot be deleted", getChannelId()); - - } - - else - { - final String exchangeName = exchangeStr.toString(); - - final ExchangeImpl exchange = virtualHost.getExchange(exchangeName); - if (exchange == null) - { - closeChannel(AMQConstant.NOT_FOUND, "No such exchange: '" + exchangeStr + "'"); - } - else - { - virtualHost.removeExchange(exchange, !ifUnused); - - ExchangeDeleteOkBody responseBody = _connection.getMethodRegistry().createExchangeDeleteOkBody(); - - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - } - } - } - catch (ExchangeIsAlternateException e) - { - closeChannel(AMQConstant.NOT_ALLOWED, "Exchange in use as an alternate exchange"); - } - catch (RequiredExchangeException e) - { - closeChannel(AMQConstant.NOT_ALLOWED, - "Exchange '" + exchangeStr + "' cannot be deleted"); - } - catch (AccessControlException e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, e.getMessage(), getChannelId()); - } - } - - @Override - public void receiveQueueBind(final AMQShortString queueName, - final AMQShortString exchange, - AMQShortString routingKey, - final boolean nowait, - final FieldTable argumentsTable) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] QueueBind[" +" queue: " + queueName + - " exchange: " + exchange + - " bindingKey: " + routingKey + - " nowait: " + nowait + " arguments: " + argumentsTable + " ]"); - } - - VirtualHostImpl virtualHost = _connection.getVirtualHost(); - AMQQueue queue; - if (queueName == null) - { - - queue = getDefaultQueue(); - - if (queue != null) - { - if (routingKey == null) - { - routingKey = AMQShortString.valueOf(queue.getName()); - } - else - { - routingKey = routingKey.intern(); - } - } - } - else - { - queue = virtualHost.getQueue(queueName.toString()); - routingKey = routingKey == null ? AMQShortString.EMPTY_STRING : routingKey.intern(); - } - - if (queue == null) - { - String message = queueName == null - ? "No default queue defined on channel and queue was null" - : "Queue " + queueName + " does not exist."; - closeChannel(AMQConstant.NOT_FOUND, message); - } - else if (isDefaultExchange(exchange)) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, - "Cannot bind the queue '" + queueName + "' to the default exchange", getChannelId()); - - } - else - { - - final String exchangeName = exchange.toString(); - - final ExchangeImpl exch = virtualHost.getExchange(exchangeName); - if (exch == null) - { - closeChannel(AMQConstant.NOT_FOUND, - "Exchange '" + exchangeName + "' does not exist."); - } - else - { - - try - { - - Map arguments = FieldTable.convertToMap(argumentsTable); - String bindingKey = String.valueOf(routingKey); - - if (!exch.isBound(bindingKey, arguments, queue)) - { - - if (!exch.addBinding(bindingKey, queue, arguments) - && ExchangeDefaults.TOPIC_EXCHANGE_CLASS.equals( - exch.getType())) - { - exch.replaceBinding(bindingKey, queue, arguments); - } - } - - if (_logger.isInfoEnabled()) - { - _logger.info("Binding queue " - + queue - + " to exchange " - + exch - + " with routing key " - + routingKey); - } - if (!nowait) - { - sync(); - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createQueueBindOkBody(); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - - } - } - catch (AccessControlException e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, e.getMessage(), getChannelId()); - } - } - } - } - - @Override - public void receiveQueueDeclare(final AMQShortString queueStr, - final boolean passive, - final boolean durable, - final boolean exclusive, - final boolean autoDelete, - final boolean nowait, - final FieldTable arguments) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] QueueDeclare[" +" queue: " + queueStr + - " passive: " + passive + - " durable: " + durable + - " exclusive: " + exclusive + - " autoDelete: " + autoDelete + " nowait: " + nowait + " arguments: " + arguments + " ]"); - } - - VirtualHostImpl virtualHost = _connection.getVirtualHost(); - - final AMQShortString queueName; - - // if we aren't given a queue name, we create one which we return to the client - if ((queueStr == null) || (queueStr.length() == 0)) - { - queueName = new AMQShortString("tmp_" + UUID.randomUUID()); - } - else - { - queueName = queueStr.intern(); - } - - AMQQueue queue; - - //TODO: do we need to check that the queue already exists with exactly the same "configuration"? - - - if (passive) - { - queue = virtualHost.getQueue(queueName.toString()); - if (queue == null) - { - closeChannel(AMQConstant.NOT_FOUND, - "Queue: '" - + queueName - + "' not found on VirtualHost '" - + virtualHost.getName() - + "'."); - } - else - { - if (!queue.verifySessionAccess(this)) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, "Queue '" - + queue.getName() - + "' is exclusive, but not created on this Connection.", getChannelId()); - } - else - { - //set this as the default queue on the channel: - setDefaultQueue(queue); - if (!nowait) - { - sync(); - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - QueueDeclareOkBody responseBody = - methodRegistry.createQueueDeclareOkBody(queueName, - queue.getQueueDepthMessages(), - queue.getConsumerCount()); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - - _logger.info("Queue " + queueName + " declared successfully"); - } - } - } - } - else - { - - try - { - Map attributes = - QueueArgumentsConverter.convertWireArgsToModel(FieldTable.convertToMap(arguments)); - final String queueNameString = AMQShortString.toString(queueName); - attributes.put(Queue.NAME, queueNameString); - attributes.put(Queue.DURABLE, durable); - - LifetimePolicy lifetimePolicy; - ExclusivityPolicy exclusivityPolicy; - - if (exclusive) - { - lifetimePolicy = autoDelete - ? LifetimePolicy.DELETE_ON_NO_OUTBOUND_LINKS - : durable ? LifetimePolicy.PERMANENT : LifetimePolicy.DELETE_ON_CONNECTION_CLOSE; - exclusivityPolicy = durable ? ExclusivityPolicy.CONTAINER : ExclusivityPolicy.CONNECTION; - } - else - { - lifetimePolicy = autoDelete ? LifetimePolicy.DELETE_ON_NO_OUTBOUND_LINKS : LifetimePolicy.PERMANENT; - exclusivityPolicy = ExclusivityPolicy.NONE; - } - - attributes.put(Queue.EXCLUSIVE, exclusivityPolicy); - attributes.put(Queue.LIFETIME_POLICY, lifetimePolicy); - - - queue = virtualHost.createQueue(attributes); - - setDefaultQueue(queue); - - if (!nowait) - { - sync(); - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - QueueDeclareOkBody responseBody = - methodRegistry.createQueueDeclareOkBody(queueName, - queue.getQueueDepthMessages(), - queue.getConsumerCount()); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - - _logger.info("Queue " + queueName + " declared successfully"); - } - } - catch (QueueExistsException qe) - { - - queue = qe.getExistingQueue(); - - if (!queue.verifySessionAccess(this)) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, "Queue '" - + queue.getName() - + "' is exclusive, but not created on this Connection.", getChannelId()); - - } - else if (queue.isExclusive() != exclusive) - { - - closeChannel(AMQConstant.ALREADY_EXISTS, - "Cannot re-declare queue '" - + queue.getName() - + "' with different exclusivity (was: " - + queue.isExclusive() - + " requested " - + exclusive - + ")"); - } - else if ((autoDelete - && queue.getLifetimePolicy() != LifetimePolicy.DELETE_ON_NO_OUTBOUND_LINKS) - || (!autoDelete && queue.getLifetimePolicy() != ((exclusive - && !durable) - ? LifetimePolicy.DELETE_ON_CONNECTION_CLOSE - : LifetimePolicy.PERMANENT))) - { - closeChannel(AMQConstant.ALREADY_EXISTS, - "Cannot re-declare queue '" - + queue.getName() - + "' with different lifetime policy (was: " - + queue.getLifetimePolicy() - + " requested autodelete: " - + autoDelete - + ")"); - } - else - { - setDefaultQueue(queue); - if (!nowait) - { - sync(); - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - QueueDeclareOkBody responseBody = - methodRegistry.createQueueDeclareOkBody(queueName, - queue.getQueueDepthMessages(), - queue.getConsumerCount()); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - - _logger.info("Queue " + queueName + " declared successfully"); - } - } - } - catch (AccessControlException e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, e.getMessage(), getChannelId()); - } - - } - } - - @Override - public void receiveQueueDelete(final AMQShortString queueName, - final boolean ifUnused, - final boolean ifEmpty, - final boolean nowait) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] QueueDelete[" +" queue: " + queueName + " ifUnused: " + ifUnused + " ifEmpty: " + ifEmpty + " nowait: " + nowait + " ]"); - } - - VirtualHostImpl virtualHost = _connection.getVirtualHost(); - sync(); - AMQQueue queue; - if (queueName == null) - { - - //get the default queue on the channel: - queue = getDefaultQueue(); - } - else - { - queue = virtualHost.getQueue(queueName.toString()); - } - - if (queue == null) - { - closeChannel(AMQConstant.NOT_FOUND, "Queue '" + queueName + "' does not exist."); - - } - else - { - if (ifEmpty && !queue.isEmpty()) - { - closeChannel(AMQConstant.IN_USE, "Queue: '" + queueName + "' is not empty."); - } - else if (ifUnused && !queue.isUnused()) - { - // TODO - Error code - closeChannel(AMQConstant.IN_USE, "Queue: '" + queueName + "' is still used."); - } - else - { - if (!queue.verifySessionAccess(this)) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, "Queue '" - + queue.getName() - + "' is exclusive, but not created on this Connection.", getChannelId()); - - } - else - { - try - { - int purged = virtualHost.removeQueue(queue); - - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - QueueDeleteOkBody responseBody = methodRegistry.createQueueDeleteOkBody(purged); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - } - catch (AccessControlException e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, e.getMessage(), getChannelId()); - - } - } - } - } - } - - @Override - public void receiveQueuePurge(final AMQShortString queueName, final boolean nowait) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] QueuePurge[" +" queue: " + queueName + " nowait: " + nowait + " ]"); - } - - VirtualHostImpl virtualHost = _connection.getVirtualHost(); - AMQQueue queue = null; - if (queueName == null && (queue = getDefaultQueue()) == null) - { - - _connection.closeConnection(AMQConstant.NOT_ALLOWED, "No queue specified.", getChannelId()); - } - else if ((queueName != null) && (queue = virtualHost.getQueue(queueName.toString())) == null) - { - closeChannel(AMQConstant.NOT_FOUND, "Queue '" + queueName + "' does not exist."); - } - else if (!queue.verifySessionAccess(this)) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, - "Queue is exclusive, but not created on this Connection.", getChannelId()); - } - else - { - try - { - long purged = queue.clearQueue(); - if (!nowait) - { - sync(); - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createQueuePurgeOkBody(purged); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - - } - } - catch (AccessControlException e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, e.getMessage(), getChannelId()); - - } - - } - } - - @Override - public void receiveQueueUnbind(final AMQShortString queueName, - final AMQShortString exchange, - final AMQShortString bindingKey, - final FieldTable arguments) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] QueueUnbind[" +" queue: " + queueName + - " exchange: " + exchange + - " bindingKey: " + bindingKey + - " arguments: " + arguments + " ]"); - } - - VirtualHostImpl virtualHost = _connection.getVirtualHost(); - - - final boolean useDefaultQueue = queueName == null; - final AMQQueue queue = useDefaultQueue - ? getDefaultQueue() - : virtualHost.getQueue(queueName.toString()); - - - if (queue == null) - { - String message = useDefaultQueue - ? "No default queue defined on channel and queue was null" - : "Queue '" + queueName + "' does not exist."; - closeChannel(AMQConstant.NOT_FOUND, message); - } - else if (isDefaultExchange(exchange)) - { - _connection.closeConnection(AMQConstant.NOT_ALLOWED, "Cannot unbind the queue '" - + queue.getName() - + "' from the default exchange", getChannelId()); - - } - else - { - - final ExchangeImpl exch = virtualHost.getExchange(exchange.toString()); - - if (exch == null) - { - closeChannel(AMQConstant.NOT_FOUND, "Exchange '" + exchange + "' does not exist."); - } - else if (!exch.hasBinding(String.valueOf(bindingKey), queue)) - { - closeChannel(AMQConstant.NOT_FOUND, "No such binding"); - } - else - { - try - { - exch.deleteBinding(String.valueOf(bindingKey), queue); - - final AMQMethodBody responseBody = _connection.getMethodRegistry().createQueueUnbindOkBody(); - sync(); - _connection.writeFrame(responseBody.generateFrame(getChannelId())); - } - catch (AccessControlException e) - { - _connection.closeConnection(AMQConstant.ACCESS_REFUSED, e.getMessage(), getChannelId()); - - } - } - - } - } - - @Override - public void receiveTxSelect() - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] TxSelect"); - } - - setLocalTransactional(); - - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - TxSelectOkBody responseBody = methodRegistry.createTxSelectOkBody(); - _connection.writeFrame(responseBody.generateFrame(_channelId)); - - } - - @Override - public void receiveTxCommit() - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] TxCommit"); - } - - - if (!isTransactional()) - { - closeChannel(AMQConstant.COMMAND_INVALID, - "Fatal error: commit called on non-transactional channel"); - } - commit(new Runnable() - { - - @Override - public void run() - { - MethodRegistry methodRegistry = _connection.getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createTxCommitOkBody(); - _connection.writeFrame(responseBody.generateFrame(_channelId)); - } - }, true); - - } - - @Override - public void receiveTxRollback() - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] TxRollback"); - } - - if (!isTransactional()) - { - closeChannel(AMQConstant.COMMAND_INVALID, - "Fatal error: rollback called on non-transactional channel"); - } - - final MethodRegistry methodRegistry = _connection.getMethodRegistry(); - final AMQMethodBody responseBody = methodRegistry.createTxRollbackOkBody(); - - Runnable task = new Runnable() - { - - public void run() - { - _connection.writeFrame(responseBody.generateFrame(_channelId)); - } - }; - - rollback(task); - - //Now resend all the unacknowledged messages back to the original subscribers. - //(Must be done after the TxnRollback-ok response). - // Why, are we not allowed to send messages back to client before the ok method? - resend(); - } - - @Override - public void receiveConfirmSelect(final boolean nowait) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + _channelId + "] ConfirmSelect [ nowait: " + nowait + " ]"); - } - _confirmOnPublish = true; - - if(!nowait) - { - _connection.writeFrame(new AMQFrame(_channelId, ConfirmSelectOkBody.INSTANCE)); - } - } - - - private void closeChannel(final AMQConstant cause, final String message) - { - _connection.closeChannelAndWriteFrame(this, cause, message); - } - - - private boolean isDefaultExchange(final AMQShortString exchangeName) - { - return exchangeName == null || AMQShortString.EMPTY_STRING.equals(exchangeName); - } - - private void setDefaultQueue(AMQQueue queue) - { - AMQQueue currentDefaultQueue = _defaultQueue; - if (queue != currentDefaultQueue) - { - if (currentDefaultQueue != null) - { - currentDefaultQueue.removeDeleteTask(_defaultQueueAssociationClearingTask); - } - if (queue != null) - { - queue.addDeleteTask(_defaultQueueAssociationClearingTask); - } - } - _defaultQueue = queue; - } - - private AMQQueue getDefaultQueue() - { - return _defaultQueue; - } - - private class DefaultQueueAssociationClearingTask implements Action - { - @Override - public void performAction(final AMQQueue queue) - { - if ( queue == _defaultQueue) - { - _defaultQueue = null; - } - } - } - - @Override - public void processPending() - { - - boolean desiredBlockingState = _blocking.get(); - if (desiredBlockingState != _wireBlockingState) - { - _wireBlockingState = desiredBlockingState; - flow(!desiredBlockingState); - _blockTime = desiredBlockingState ? System.currentTimeMillis() : 0; - } - - for(ConsumerTarget target : _tag2SubscriptionTargetMap.values()) - { - target.processPending(); - } - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQMessage.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQMessage.java deleted file mode 100644 index faa3831d70..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQMessage.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.protocol.v0_8; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.AbstractServerMessageImpl; -import org.apache.qpid.server.store.StoredMessage; - -/** - * A deliverable message. - */ -public class AMQMessage extends AbstractServerMessageImpl -{ - private final long _size; - - public AMQMessage(StoredMessage handle) - { - this(handle, null); - } - - public AMQMessage(StoredMessage handle, Object connectionReference) - { - super(handle, connectionReference); - _size = handle.getMetaData().getContentSize(); - } - - public MessageMetaData getMessageMetaData() - { - return getStoredMessage().getMetaData(); - } - - public ContentHeaderBody getContentHeaderBody() - { - return getMessageMetaData().getContentHeaderBody(); - } - - public String getInitialRoutingAddress() - { - MessageMetaData messageMetaData = getMessageMetaData(); - if (messageMetaData != null) - { - AMQShortString routingKey = messageMetaData.getMessagePublishInfo().getRoutingKey(); - if (routingKey != null) - { - return routingKey.asString(); - } - } - return null; - } - - public AMQMessageHeader getMessageHeader() - { - return getMessageMetaData().getMessageHeader(); - } - - public MessagePublishInfo getMessagePublishInfo() - { - return getMessageMetaData().getMessagePublishInfo(); - } - - public long getArrivalTime() - { - return getMessageMetaData().getArrivalTime(); - } - - public long getSize() - { - return _size; - } - - public boolean isImmediate() - { - return getMessagePublishInfo().isImmediate(); - } - - public boolean isMandatory() - { - return getMessagePublishInfo().isMandatory(); - } - - public long getExpiration() - { - return getMessageHeader().getExpiration(); - } - - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQNoMethodHandlerException.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQNoMethodHandlerException.java deleted file mode 100644 index 42250190b4..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQNoMethodHandlerException.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.protocol.v0_8; - -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. - * - *

- * 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 evt) - { - super("AMQMethodEvent " + evt + " was not processed by any listener on Broker."); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQProtocolEngine.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQProtocolEngine.java deleted file mode 100644 index b1f2a6e841..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQProtocolEngine.java +++ /dev/null @@ -1,2033 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.v0_8; - -import java.io.IOException; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.security.AccessControlException; -import java.security.AccessController; -import java.security.Principal; -import java.security.PrivilegedAction; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Queue; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -import javax.security.auth.Subject; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQConnectionException; -import org.apache.qpid.AMQException; -import org.apache.qpid.codec.AMQDecoder; -import org.apache.qpid.common.QpidProperties; -import org.apache.qpid.common.ServerPropertyNames; -import org.apache.qpid.framing.*; -import org.apache.qpid.properties.ConnectionStartProperties; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.configuration.BrokerProperties; -import org.apache.qpid.server.connection.ConnectionPrincipal; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.LogSubject; -import org.apache.qpid.server.logging.messages.ConnectionMessages; -import org.apache.qpid.server.logging.subjects.ConnectionLogSubject; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Consumer; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.State; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.protocol.AMQConnectionModel; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.protocol.SessionModelListener; -import org.apache.qpid.server.security.SubjectCreator; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; -import org.apache.qpid.server.security.auth.SubjectAuthenticationResult; -import org.apache.qpid.server.stats.StatisticsCounter; -import org.apache.qpid.server.store.StoreException; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.server.util.ServerScopedRuntimeException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.ByteBufferSender; -import org.apache.qpid.transport.SenderClosedException; -import org.apache.qpid.transport.SenderException; -import org.apache.qpid.transport.TransportException; -import org.apache.qpid.transport.network.NetworkConnection; - -public class AMQProtocolEngine implements ServerProtocolEngine, - AMQConnectionModel, - ServerMethodProcessor -{ - - - - enum ConnectionState - { - INIT, - AWAIT_START_OK, - AWAIT_SECURE_OK, - AWAIT_TUNE_OK, - AWAIT_OPEN, - OPEN - } - - private static final Logger _logger = LoggerFactory.getLogger(AMQProtocolEngine.class); - - // 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 static final String BROKER_DEBUG_BINARY_DATA_LENGTH = "broker.debug.binaryDataLength"; - private static final int DEFAULT_DEBUG_BINARY_DATA_LENGTH = 80; - private static final long AWAIT_CLOSED_TIMEOUT = 60000; - private final AmqpPort _port; - private final long _creationTime; - private final AtomicBoolean _stateChanged = new AtomicBoolean(); - private final AtomicReference> _workListener = new AtomicReference<>(); - - private AMQShortString _contextKey; - - private String _clientVersion = null; - private String _clientProduct = null; - private String _remoteProcessPid = null; - - private volatile VirtualHostImpl _virtualHost; - - private final Map _channelMap = - new HashMap<>(); - private final CopyOnWriteArrayList _sessionListeners = - new CopyOnWriteArrayList<>(); - - private final AMQChannel[] _cachedChannels = new AMQChannel[CHANNEL_CACHE_SIZE + 1]; - - private ConnectionState _state = ConnectionState.INIT; - - /** - * The channels that the latest call to {@link #received(ByteBuffer)} applied to. - * Used so we know which channels we need to call {@link AMQChannel#receivedComplete()} - * on after handling the frames. - */ - private final Set _channelsForCurrentMessage = new HashSet<>(); - - private AMQDecoder _decoder; - - private SaslServer _saslServer; - - private volatile boolean _closed; - - private long _maxNoOfChannels; - - private ProtocolVersion _protocolVersion = ProtocolVersion.getLatestSupportedVersion(); - private final MethodRegistry _methodRegistry = new MethodRegistry(_protocolVersion); - private final List> _connectionCloseTaskList = - new CopyOnWriteArrayList<>(); - - private final Queue> _asyncTaskList = - new ConcurrentLinkedQueue<>(); - - private Map _closingChannelsList = new ConcurrentHashMap<>(); - private ProtocolOutputConverter _protocolOutputConverter; - private final Subject _authorizedSubject = new Subject(); - - private final long _connectionId; - private Object _reference = new Object(); - - private LogSubject _logSubject; - - private volatile long _lastIoTime; - - private long _writtenBytes; - - private int _maxFrameSize; - private final AtomicBoolean _closing = new AtomicBoolean(false); - - private final StatisticsCounter _messagesDelivered, _dataDelivered, _messagesReceived, _dataReceived; - - private NetworkConnection _network; - private ByteBufferSender _sender; - - private volatile boolean _deferFlush; - private volatile long _lastReceivedTime = System.currentTimeMillis(); - private volatile long _lastWriteTime = System.currentTimeMillis(); - private boolean _blocking; - - private final Broker _broker; - private final Transport _transport; - - private volatile boolean _closeWhenNoRoute; - private volatile boolean _stopped; - private long _readBytes; - private boolean _authenticated; - private boolean _compressionSupported; - private int _messageCompressionThreshold; - private int _currentClassId; - private int _currentMethodId; - private int _binaryDataLimit; - private long _maxMessageSize; - private volatile boolean _transportBlockedForWriting; - - private final AtomicReference _messageAssignmentSuspended = new AtomicReference<>(); - - - @Override - public boolean isMessageAssignmentSuspended() - { - Thread lock = _messageAssignmentSuspended.get(); - return lock != null && _messageAssignmentSuspended.get() != Thread.currentThread(); - } - - @Override - public void setMessageAssignmentSuspended(final boolean messageAssignmentSuspended) - { - _messageAssignmentSuspended.set(messageAssignmentSuspended ? Thread.currentThread() : null); - for(AMQSessionModel session : getSessionModels()) - { - for (Consumer consumer : session.getConsumers()) - { - ConsumerImpl consumerImpl = (ConsumerImpl) consumer; - if (!messageAssignmentSuspended) - { - consumerImpl.getTarget().notifyCurrentState(); - } - else - { - // ensure that by the time the method returns, no consumer can be in the process of - // delivering a message. - consumerImpl.getSendLock(); - consumerImpl.releaseSendLock(); - } - } - } - } - - - public AMQProtocolEngine(Broker broker, - final NetworkConnection network, - final long connectionId, - AmqpPort port, - Transport transport) - { - _broker = broker; - _port = port; - _transport = transport; - _maxNoOfChannels = broker.getConnection_sessionCountLimit(); - _decoder = new BrokerDecoder(this); - _connectionId = connectionId; - _logSubject = new ConnectionLogSubject(this); - _binaryDataLimit = _broker.getContextKeys(false).contains(BROKER_DEBUG_BINARY_DATA_LENGTH) - ? _broker.getContextValue(Integer.class, BROKER_DEBUG_BINARY_DATA_LENGTH) - : DEFAULT_DEBUG_BINARY_DATA_LENGTH; - - int maxMessageSize = port.getContextValue(Integer.class, AmqpPort.PORT_MAX_MESSAGE_SIZE); - _maxMessageSize = (maxMessageSize > 0) ? (long) maxMessageSize : Long.MAX_VALUE; - - _authorizedSubject.getPrincipals().add(new ConnectionPrincipal(this)); - runAsSubject(new PrivilegedAction() - { - - @Override - public Void run() - { - setNetworkConnection(network); - - getEventLogger().message(ConnectionMessages.OPEN(null, null, null, null, false, false, false, false)); - - _closeWhenNoRoute = _broker.getConnection_closeWhenNoRoute(); - - return null; - } - }); - - _messagesDelivered = new StatisticsCounter("messages-delivered-" + _connectionId); - _dataDelivered = new StatisticsCounter("data-delivered-" + _connectionId); - _messagesReceived = new StatisticsCounter("messages-received-" + _connectionId); - _dataReceived = new StatisticsCounter("data-received-" + _connectionId); - _creationTime = System.currentTimeMillis(); - } - - private T runAsSubject(PrivilegedAction action) - { - return Subject.doAs(getAuthorizedSubject(), action); - } - - private boolean runningAsSubject() - { - return getAuthorizedSubject().equals(Subject.getSubject(AccessController.getContext())); - } - - @Override - public Subject getSubject() - { - return _authorizedSubject; - } - - @Override - public boolean isTransportBlockedForWriting() - { - return _transportBlockedForWriting; - } - - @Override - public void setTransportBlockedForWriting(final boolean blocked) - { - _transportBlockedForWriting = blocked; - for(AMQChannel channel : _channelMap.values()) - { - channel.transportStateChanged(); - } - } - - public void setNetworkConnection(NetworkConnection network) - { - setNetworkConnection(network, network.getSender()); - } - - public void setNetworkConnection(NetworkConnection network, ByteBufferSender sender) - { - _network = network; - _sender = sender; - } - - public void setMaxFrameSize(int frameMax) - { - _maxFrameSize = frameMax; - _decoder.setMaxFrameSize(frameMax); - } - - public long getMaxFrameSize() - { - return _maxFrameSize; - } - - public boolean isClosing() - { - return _closing.get(); - } - - - - public ClientDeliveryMethod createDeliveryMethod(int channelId) - { - return new WriteDeliverMethod(channelId); - } - - public void received(final ByteBuffer msg) - { - Subject.doAs(_authorizedSubject, new PrivilegedAction() - { - @Override - public Void run() - { - - final long arrivalTime = System.currentTimeMillis(); - if (!_authenticated && - (arrivalTime - _creationTime) > _port.getContextValue(Long.class, - Port.CONNECTION_MAXIMUM_AUTHENTICATION_DELAY)) - { - _logger.warn("Connection has taken more than " - + _port.getContextValue(Long.class, Port.CONNECTION_MAXIMUM_AUTHENTICATION_DELAY) - + "ms to establish identity. Closing as possible DoS."); - getEventLogger().message(ConnectionMessages.IDLE_CLOSE()); - closeNetworkConnection(); - } - _lastReceivedTime = arrivalTime; - _lastIoTime = arrivalTime; - _readBytes += msg.remaining(); - - try - { - _decoder.decodeBuffer(msg); - receivedComplete(); - } - catch (ConnectionScopedRuntimeException e) - { - _logger.error("Unexpected exception", e); - closeNetworkConnection(); - } - catch (AMQProtocolVersionException e) - { - _logger.error("Unexpected protocol version", e); - closeNetworkConnection(); - } - catch (SenderClosedException e) - { - _logger.debug("Sender was closed abruptly, closing network.", e); - closeNetworkConnection(); - } - catch (SenderException e) - { - _logger.info("Unexpected exception on send, closing network.", e); - closeNetworkConnection(); - } - catch (TransportException e) - { - _logger.error("Unexpected transport exception", e); - closeNetworkConnection(); - } - catch (AMQFrameDecodingException e) - { - _logger.error("Frame decoding", e); - closeNetworkConnection(); - } - catch (IOException e) - { - _logger.error("I/O Exception", e); - closeNetworkConnection(); - } - catch (StoreException e) - { - if (_virtualHost.getState() == State.ACTIVE) - { - throw e; - } - else - { - _logger.error("Store Exception ignored as virtual host no longer active", e); - } - } - return null; - } - }); - - } - - private void receivedComplete() - { - RuntimeException exception = null; - - for (AMQChannel channel : _channelsForCurrentMessage) - { - try - { - channel.receivedComplete(); - } - catch(RuntimeException exceptionForThisChannel) - { - if(exception == null) - { - exception = exceptionForThisChannel; - } - _logger.error("Error informing channel that receiving is complete. Channel: " + channel, - exceptionForThisChannel); - } - } - - _channelsForCurrentMessage.clear(); - - if(exception != null) - { - throw exception; - } - } - - - void channelRequiresSync(final AMQChannel amqChannel) - { - _channelsForCurrentMessage.add(amqChannel); - } - - private synchronized void protocolInitiationReceived(ProtocolInitiation pi) - { - // this ensures the codec never checks for a PI message again - _decoder.setExpectProtocolInitiation(false); - try - { - // Log incoming protocol negotiation request - getEventLogger().message(ConnectionMessages.OPEN(null, - pi.getProtocolMajor() + "-" + pi.getProtocolMinor(), - null, - null, - false, - true, - false, - false)); - - ProtocolVersion pv = pi.checkVersion(); // Fails if not correct - - setProtocolVersion(pv); - - StringBuilder mechanismBuilder = new StringBuilder(); - SubjectCreator subjectCreator = _port.getAuthenticationProvider().getSubjectCreator(_transport.isSecure()); - for(String mechanismName : subjectCreator.getMechanisms()) - { - if(mechanismBuilder.length() != 0) - { - mechanismBuilder.append(' '); - } - mechanismBuilder.append(mechanismName); - } - String mechanisms = mechanismBuilder.toString(); - - String locales = "en_US"; - - - FieldTable serverProperties = FieldTableFactory.newFieldTable(); - - serverProperties.setString(ServerPropertyNames.PRODUCT, - QpidProperties.getProductName()); - serverProperties.setString(ServerPropertyNames.VERSION, - QpidProperties.getReleaseVersion()); - serverProperties.setString(ServerPropertyNames.QPID_BUILD, - QpidProperties.getBuildVersion()); - serverProperties.setString(ServerPropertyNames.QPID_INSTANCE_NAME, - _broker.getName()); - serverProperties.setString(ConnectionStartProperties.QPID_CLOSE_WHEN_NO_ROUTE, - String.valueOf(_closeWhenNoRoute)); - serverProperties.setString(ConnectionStartProperties.QPID_MESSAGE_COMPRESSION_SUPPORTED, - String.valueOf(_broker.isMessageCompressionEnabled())); - serverProperties.setString(ConnectionStartProperties.QPID_CONFIRMED_PUBLISH_SUPPORTED, Boolean.TRUE.toString()); - - AMQMethodBody responseBody = getMethodRegistry().createConnectionStartBody((short) getProtocolMajorVersion(), - (short) pv.getActualMinorVersion(), - serverProperties, - mechanisms.getBytes(), - locales.getBytes()); - writeFrame(responseBody.generateFrame(0)); - _state = ConnectionState.AWAIT_START_OK; - - _sender.flush(); - - } - catch (AMQException e) - { - _logger.info("Received unsupported protocol initiation for protocol version: " + getProtocolVersion()); - - writeFrame(new ProtocolInitiation(ProtocolVersion.getLatestSupportedVersion())); - _sender.flush(); - } - } - - - - - public synchronized void writeFrame(AMQDataBlock frame) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("SEND: " + frame); - } - - try - { - _writtenBytes += frame.writePayload(_sender); - } - catch (IOException e) - { - throw new ServerScopedRuntimeException(e); - } - - - final long time = System.currentTimeMillis(); - _lastIoTime = time; - _lastWriteTime = time; - - if(!_deferFlush) - { - _sender.flush(); - } - } - - public AMQShortString getContextKey() - { - return _contextKey; - } - - public void setContextKey(AMQShortString contextKey) - { - _contextKey = contextKey; - } - - public List getChannels() - { - synchronized (_channelMap) - { - return new ArrayList<>(_channelMap.values()); - } - } - - 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) - { - final int channelId = channel.getChannelId(); - - synchronized (_channelMap) - { - _channelMap.put(channel.getChannelId(), channel); - sessionAdded(channel); - if(_blocking) - { - channel.block(); - } - } - - if (((channelId & CHANNEL_CACHE_SIZE) == channelId)) - { - _cachedChannels[channelId] = channel; - } - } - - private void sessionAdded(final AMQSessionModel session) - { - for(SessionModelListener l : _sessionListeners) - { - l.sessionAdded(session); - } - } - - private void sessionRemoved(final AMQSessionModel session) - { - for(SessionModelListener l : _sessionListeners) - { - l.sessionRemoved(session); - } - } - - public long getMaximumNumberOfChannels() - { - return _maxNoOfChannels; - } - - public void setMaximumNumberOfChannels(Long value) - { - _maxNoOfChannels = value; - } - - - void closeChannel(AMQChannel channel) - { - closeChannel(channel, null, null, false); - } - - public void closeChannelAndWriteFrame(AMQChannel channel, AMQConstant cause, String message) - { - writeFrame(new AMQFrame(channel.getChannelId(), - getMethodRegistry().createChannelCloseBody(cause.getCode(), - AMQShortString.validValueOf(message), - _currentClassId, - _currentMethodId))); - closeChannel(channel, cause, message, true); - } - - public void closeChannel(int channelId, AMQConstant cause, String message) - { - final AMQChannel channel = getChannel(channelId); - if (channel == null) - { - throw new IllegalArgumentException("Unknown channel id"); - } - closeChannel(channel, cause, message, true); - } - - void closeChannel(AMQChannel channel, AMQConstant cause, String message, boolean mark) - { - int channelId = channel.getChannelId(); - try - { - channel.close(cause, message); - if(mark) - { - markChannelAwaitingCloseOk(channelId); - } - } - finally - { - removeChannel(channelId); - } - } - - - public void closeChannelOk(int 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) - { - AMQChannel session; - synchronized (_channelMap) - { - session = _channelMap.remove(channelId); - if ((channelId & CHANNEL_CACHE_SIZE) == channelId) - { - _cachedChannels[channelId] = null; - } - } - sessionRemoved(session); - } - - private void initHeartbeats(int delay) - { - if (delay > 0) - { - _network.setMaxWriteIdle(delay); - _network.setMaxReadIdle(BrokerProperties.HEARTBEAT_TIMEOUT_FACTOR * delay); - } - else - { - _network.setMaxWriteIdle(0); - _network.setMaxReadIdle(0); - } - } - - private void closeAllChannels() - { - try - { - RuntimeException firstException = null; - for (AMQChannel channel : getChannels()) - { - try - { - channel.close(); - } - catch (RuntimeException re) - { - if (!(re instanceof ConnectionScopedRuntimeException)) - { - _logger.error("Unexpected exception closing channel", re); - } - firstException = re; - } - } - - if (firstException != null) - { - throw firstException; - } - } - finally - { - synchronized (_channelMap) - { - _channelMap.clear(); - } - for (int i = 0; i <= CHANNEL_CACHE_SIZE; i++) - { - _cachedChannels[i] = null; - } - - } - } - - private void closeConnectionInternal(final boolean connectionDropped) - { - - if(runningAsSubject()) - { - if(_closing.compareAndSet(false,true)) - { - // force sync of outstanding async work - try - { - receivedComplete(); - } - finally - { - - finishClose(connectionDropped); - } - - } - else - { - awaitClosed(); - } - } - else - { - runAsSubject(new PrivilegedAction() - { - @Override - public Object run() - { - closeConnectionInternal(connectionDropped); - return null; - } - }); - - } - } - - private void finishClose(boolean connectionDropped) - { - if (!_closed) - { - - try - { - if (_virtualHost != null) - { - _virtualHost.getConnectionRegistry().deregisterConnection(this); - } - closeAllChannels(); - } - finally - { - try - { - for (Action task : _connectionCloseTaskList) - { - task.performAction(this); - } - } - finally - { - synchronized (this) - { - _closed = true; - notifyAll(); - } - getEventLogger().message(_logSubject, connectionDropped ? ConnectionMessages.DROPPED_CONNECTION() : ConnectionMessages.CLOSE()); - } - } - } - } - - private void awaitClosed() - { - synchronized(this) - { - final long endTime = System.currentTimeMillis() + AWAIT_CLOSED_TIMEOUT; - - while(!_closed && endTime > System.currentTimeMillis()) - { - try - { - wait(1000); - } - catch (InterruptedException e) - { - Thread.currentThread().interrupt(); - break; - } - } - - if (!_closed) - { - throw new ConnectionScopedRuntimeException("Connection " + this + " failed to become closed within " + AWAIT_CLOSED_TIMEOUT + "ms."); - } - } - } - - private void closeConnection(int channelId, AMQConnectionException e) - { - - if (_logger.isInfoEnabled()) - { - _logger.info("Closing connection due to: " + e); - } - closeConnection(channelId, e.getCloseFrame()); - } - - - void closeConnection(AMQConstant errorCode, - String message, int channelId) - { - - if (_logger.isInfoEnabled()) - { - _logger.info("Closing connection due to: " + message); - } - closeConnection(channelId, new AMQFrame(0, new ConnectionCloseBody(getProtocolVersion(), errorCode.getCode(), AMQShortString.validValueOf(message), _currentClassId, _currentMethodId))); - } - - private void closeConnection(int channelId, AMQFrame frame) - { - if(!_closing.get()) - { - try - { - markChannelAwaitingCloseOk(channelId); - closeConnectionInternal(false); - } - finally - { - try - { - writeFrame(frame); - } - finally - { - closeNetworkConnection(); - } - } - } - else - { - awaitClosed(); - } - } - - public void closeNetworkConnection() - { - _network.close(); - } - - public String toString() - { - return getRemoteAddress() + "(" + (getAuthorizedPrincipal() == null ? "?" : getAuthorizedPrincipal().getName() + ")"); - } - - private String getLocalFQDN() - { - SocketAddress address = _network.getLocalAddress(); - if (address instanceof InetSocketAddress) - { - return ((InetSocketAddress) address).getHostName(); - } - else - { - throw new IllegalArgumentException("Unsupported socket address class: " + address); - } - } - - public SaslServer getSaslServer() - { - return _saslServer; - } - - public void setSaslServer(SaslServer saslServer) - { - _saslServer = saslServer; - } - - public void setClientProperties(FieldTable clientProperties) - { - if (clientProperties != null) - { - String closeWhenNoRoute = clientProperties.getString(ConnectionStartProperties.QPID_CLOSE_WHEN_NO_ROUTE); - if (closeWhenNoRoute != null) - { - _closeWhenNoRoute = Boolean.parseBoolean(closeWhenNoRoute); - if(_logger.isDebugEnabled()) - { - _logger.debug("Client set closeWhenNoRoute=" + _closeWhenNoRoute + " for protocol engine " + this); - } - } - String compressionSupported = clientProperties.getString(ConnectionStartProperties.QPID_MESSAGE_COMPRESSION_SUPPORTED); - if (compressionSupported != null) - { - _compressionSupported = Boolean.parseBoolean(compressionSupported); - if(_logger.isDebugEnabled()) - { - _logger.debug("Client set compressionSupported=" + _compressionSupported + " for protocol engine " + this); - } - } - - _clientVersion = clientProperties.getString(ConnectionStartProperties.VERSION_0_8); - _clientProduct = clientProperties.getString(ConnectionStartProperties.PRODUCT); - _remoteProcessPid = clientProperties.getString(ConnectionStartProperties.PID); - - String clientId = clientProperties.getString(ConnectionStartProperties.CLIENT_ID_0_8); - if (clientId != null) - { - setContextKey(new AMQShortString(clientId)); - } - - getEventLogger().message(ConnectionMessages.OPEN(clientId, - _protocolVersion.toString(), - _clientVersion, - _clientProduct, - true, - true, - true, - true)); - } - } - - private void setProtocolVersion(ProtocolVersion pv) - { - _protocolVersion = pv; - _methodRegistry.setProtocolVersion(_protocolVersion); - _protocolOutputConverter = new ProtocolOutputConverterImpl(this); - } - - public byte getProtocolMajorVersion() - { - return _protocolVersion.getMajorVersion(); - } - - public ProtocolVersion getProtocolVersion() - { - return _protocolVersion; - } - - public byte getProtocolMinorVersion() - { - return _protocolVersion.getMinorVersion(); - } - - public MethodRegistry getRegistry() - { - return getMethodRegistry(); - } - - public VirtualHostImpl getVirtualHost() - { - return _virtualHost; - } - - public void setVirtualHost(VirtualHostImpl virtualHost) - { - _virtualHost = virtualHost; - - _virtualHost.getConnectionRegistry().registerConnection(this); - - - _messageCompressionThreshold = virtualHost.getContextValue(Integer.class, - Broker.MESSAGE_COMPRESSION_THRESHOLD_SIZE); - if(_messageCompressionThreshold <= 0) - { - _messageCompressionThreshold = Integer.MAX_VALUE; - } - } - - public void addDeleteTask(Action task) - { - _connectionCloseTaskList.add(task); - } - - public void removeDeleteTask(Action task) - { - _connectionCloseTaskList.remove(task); - } - - public ProtocolOutputConverter getProtocolOutputConverter() - { - return _protocolOutputConverter; - } - - public void setAuthorizedSubject(final Subject authorizedSubject) - { - if (authorizedSubject == null) - { - throw new IllegalArgumentException("authorizedSubject cannot be null"); - } - - _authenticated = true; - _authorizedSubject.getPrincipals().addAll(authorizedSubject.getPrincipals()); - _authorizedSubject.getPrivateCredentials().addAll(authorizedSubject.getPrivateCredentials()); - _authorizedSubject.getPublicCredentials().addAll(authorizedSubject.getPublicCredentials()); - - } - - public Subject getAuthorizedSubject() - { - return _authorizedSubject; - } - - public Principal getAuthorizedPrincipal() - { - - return _authorizedSubject.getPrincipals(AuthenticatedPrincipal.class).size() == 0 ? null : AuthenticatedPrincipal.getAuthenticatedPrincipalFromSubject(_authorizedSubject); - } - - public SocketAddress getRemoteAddress() - { - return _network.getRemoteAddress(); - } - - @Override - public String getRemoteProcessPid() - { - return _remoteProcessPid; - } - - public SocketAddress getLocalAddress() - { - return _network.getLocalAddress(); - } - - public Principal getPeerPrincipal() - { - return _network.getPeerPrincipal(); - } - - public MethodRegistry getMethodRegistry() - { - return _methodRegistry; - } - - public void closed() - { - try - { - try - { - closeConnectionInternal(true); - } - finally - { - closeNetworkConnection(); - } - } - catch (ConnectionScopedRuntimeException | TransportException e) - { - _logger.error("Could not close protocol engine", e); - } - } - - @Override - public void encryptedTransport() - { - } - - public void readerIdle() - { - Subject.doAs(_authorizedSubject, new PrivilegedAction() - { - @Override - public Object run() - { - getEventLogger().message(ConnectionMessages.IDLE_CLOSE()); - _network.close(); - return null; - } - }); - } - - public synchronized void writerIdle() - { - writeFrame(HeartbeatBody.FRAME); - } - - public void exception(Throwable throwable) - { - // noop - exception method is not used by new i/o layer - } - - public long getReadBytes() - { - return _readBytes; - } - - public long getWrittenBytes() - { - return _writtenBytes; - } - - public long getLastIoTime() - { - return _lastIoTime; - } - - @Override - public AmqpPort getPort() - { - return _port; - } - - @Override - public Transport getTransport() - { - return _transport; - } - - @Override - public void stop() - { - _stopped = true; - } - - @Override - public boolean isStopped() - { - return _stopped; - } - - @Override - public String getVirtualHostName() - { - return _virtualHost == null ? null : _virtualHost.getName(); - } - - public long getLastReceivedTime() - { - return _lastReceivedTime; - } - - public String getClientVersion() - { - return _clientVersion; - } - - @Override - public String getClientProduct() - { - return _clientProduct; - } - - public long getSessionCountLimit() - { - return getMaximumNumberOfChannels(); - } - - public boolean isDurable() - { - return false; - } - - public long getConnectionId() - { - return _connectionId; - } - - public String getAddress() - { - return String.valueOf(getRemoteAddress()); - } - - public void closeSessionAsync(final AMQChannel session, final AMQConstant cause, final String message) - { - addAsyncTask(new Action() - { - - @Override - public void performAction(final AMQProtocolEngine object) - { - int channelId = session.getChannelId(); - closeChannel(channelId, cause, message); - - MethodRegistry methodRegistry = getMethodRegistry(); - ChannelCloseBody responseBody = - methodRegistry.createChannelCloseBody( - cause.getCode(), - AMQShortString.validValueOf(message), - 0, 0); - - writeFrame(responseBody.generateFrame(channelId)); - } - }); - - } - - public void closeAsync(final AMQConstant cause, final String message) - { - Action action = new Action() - { - @Override - public void performAction(final AMQProtocolEngine object) - { - closeConnection(0, new AMQConnectionException(cause, message, 0, 0, - getMethodRegistry(), - null)); - - } - }; - addAsyncTask(action); - } - - private void addAsyncTask(final Action action) - { - _asyncTaskList.add(action); - notifyWork(); - } - - public void block() - { - synchronized (_channelMap) - { - if(!_blocking) - { - _blocking = true; - for(AMQChannel channel : _channelMap.values()) - { - channel.block(); - } - } - } - } - - public void unblock() - { - synchronized (_channelMap) - { - if(_blocking) - { - _blocking = false; - for(AMQChannel channel : _channelMap.values()) - { - channel.unblock(); - } - } - } - } - - public boolean isClosed() - { - return _closed; - } - - public List getSessionModels() - { - return new ArrayList<>(getChannels()); - } - - public LogSubject getLogSubject() - { - return _logSubject; - } - - public void registerMessageDelivered(long messageSize) - { - _messagesDelivered.registerEvent(1L); - _dataDelivered.registerEvent(messageSize); - _virtualHost.registerMessageDelivered(messageSize); - } - - public void registerMessageReceived(long messageSize, long timestamp) - { - _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 String getRemoteAddressString() - { - return String.valueOf(getRemoteAddress()); - } - - public String getClientId() - { - return String.valueOf(getContextKey()); - } - - @Override - public String getRemoteContainerName() - { - return String.valueOf(getContextKey()); - } - - @Override - public void addSessionListener(final SessionModelListener listener) - { - _sessionListeners.add(listener); - } - - @Override - public void removeSessionListener(final SessionModelListener listener) - { - _sessionListeners.remove(listener); - } - - public void setDeferFlush(boolean deferFlush) - { - _deferFlush = deferFlush; - } - - @Override - public void receiveChannelOpen(final int channelId) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV[" + channelId + "] ChannelOpen"); - } - assertState(ConnectionState.OPEN); - - // Protect the broker against out of order frame request. - if (_virtualHost == null) - { - closeConnection(AMQConstant.COMMAND_INVALID, - "Virtualhost has not yet been set. ConnectionOpen has not been called.", channelId); - } - else if(getChannel(channelId) != null || channelAwaitingClosure(channelId)) - { - closeConnection(AMQConstant.CHANNEL_ERROR, "Channel " + channelId + " already exists", channelId); - } - else if(channelId > getMaximumNumberOfChannels()) - { - closeConnection(AMQConstant.CHANNEL_ERROR, - "Channel " + channelId + " cannot be created as the max allowed channel id is " - + getMaximumNumberOfChannels(), - channelId); - } - else - { - _logger.info("Connecting to: " + _virtualHost.getName()); - - final AMQChannel channel = new AMQChannel(this, channelId, _virtualHost.getMessageStore()); - - addChannel(channel); - - ChannelOpenOkBody response; - - - response = getMethodRegistry().createChannelOpenOkBody(); - - - writeFrame(response.generateFrame(channelId)); - } - } - - void assertState(final ConnectionState requiredState) - { - if(_state != requiredState) - { - closeConnection(AMQConstant.COMMAND_INVALID, "Command Invalid", 0); - - } - } - - @Override - public void receiveConnectionOpen(AMQShortString virtualHostName, - AMQShortString capabilities, - boolean insist) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV ConnectionOpen[" +" virtualHost: " + virtualHostName + " capabilities: " + capabilities + " insist: " + insist + " ]"); - } - - String virtualHostStr; - if ((virtualHostName != null) && virtualHostName.charAt(0) == '/') - { - virtualHostStr = virtualHostName.toString().substring(1); - } - else - { - virtualHostStr = virtualHostName == null ? null : virtualHostName.toString(); - } - - VirtualHostImpl virtualHost = ((AmqpPort)getPort()).getVirtualHost(virtualHostStr); - - if (virtualHost == null) - { - closeConnection(AMQConstant.NOT_FOUND, - "Unknown virtual host: '" + virtualHostName + "'",0); - - } - else - { - // Check virtualhost access - if (virtualHost.getState() != State.ACTIVE) - { - String redirectHost = virtualHost.getRedirectHost(getPort()); - if(redirectHost != null) - { - closeConnection(0, new AMQFrame(0,new ConnectionRedirectBody(getProtocolVersion(),AMQShortString.valueOf(redirectHost), null))); - } - else - { - closeConnection(AMQConstant.CONNECTION_FORCED, - "Virtual host '" + virtualHost.getName() + "' is not active", 0); - } - - } - else - { - setVirtualHost(virtualHost); - try - { - - if(virtualHost.authoriseCreateConnection(this)) - { - if (getContextKey() == null) - { - setContextKey(new AMQShortString(Long.toString(System.currentTimeMillis()))); - } - - MethodRegistry methodRegistry = getMethodRegistry(); - AMQMethodBody responseBody = methodRegistry.createConnectionOpenOkBody(virtualHostName); - - writeFrame(responseBody.generateFrame(0)); - _state = ConnectionState.OPEN; - - } - else - { - closeConnection(AMQConstant.ACCESS_REFUSED, "Connection refused",0); - } - } - catch (AccessControlException e) - { - closeConnection(AMQConstant.ACCESS_REFUSED, e.getMessage(), 0); - } - } - } - } - - @Override - public void receiveConnectionClose(final int replyCode, - final AMQShortString replyText, - final int classId, - final int methodId) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV ConnectionClose[" +" replyCode: " + replyCode + " replyText: " + replyText + " classId: " + classId + " methodId: " + methodId + " ]"); - } - - if (_logger.isInfoEnabled()) - { - _logger.info("ConnectionClose received with reply code/reply text " + replyCode + "/" + - replyText + " for " + this); - } - try - { - closeConnectionInternal(false); - - MethodRegistry methodRegistry = getMethodRegistry(); - ConnectionCloseOkBody responseBody = methodRegistry.createConnectionCloseOkBody(); - writeFrame(responseBody.generateFrame(0)); - } - catch (Exception e) - { - _logger.error("Error closing connection for " + getRemoteAddressString(), e); - } - finally - { - closeNetworkConnection(); - } - } - - @Override - public void receiveConnectionCloseOk() - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV ConnectionCloseOk"); - } - - _logger.info("Received Connection-close-ok"); - - try - { - closeConnectionInternal(false); - } - catch (Exception e) - { - _logger.error("Error closing connection: " + getRemoteAddressString(), e); - } - finally - { - closeNetworkConnection(); - } - - } - - @Override - public void receiveConnectionSecureOk(final byte[] response) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV ConnectionSecureOk[ response: ******** ] "); - } - - assertState(ConnectionState.AWAIT_SECURE_OK); - - Broker broker = getBroker(); - - SubjectCreator subjectCreator = getSubjectCreator(); - - SaslServer ss = getSaslServer(); - if (ss == null) - { - closeConnection(AMQConstant.INTERNAL_ERROR, "No SASL context set up in connection",0 ); - } - MethodRegistry methodRegistry = getMethodRegistry(); - SubjectAuthenticationResult authResult = subjectCreator.authenticate(ss, response); - switch (authResult.getStatus()) - { - case ERROR: - Exception cause = authResult.getCause(); - - _logger.info("Authentication failed:" + (cause == null ? "" : cause.getMessage())); - - closeConnection(AMQConstant.NOT_ALLOWED, "Authentication failed",0); - - disposeSaslServer(); - break; - case SUCCESS: - if (_logger.isInfoEnabled()) - { - _logger.info("Connected as: " + authResult.getSubject()); - } - - int frameMax = broker.getContextValue(Integer.class, Broker.BROKER_FRAME_SIZE); - - if (frameMax <= 0) - { - frameMax = Integer.MAX_VALUE; - } - - ConnectionTuneBody tuneBody = - methodRegistry.createConnectionTuneBody(broker.getConnection_sessionCountLimit(), - frameMax, - broker.getConnection_heartBeatDelay()); - writeFrame(tuneBody.generateFrame(0)); - _state = ConnectionState.AWAIT_TUNE_OK; - setAuthorizedSubject(authResult.getSubject()); - disposeSaslServer(); - break; - case CONTINUE: - - ConnectionSecureBody - secureBody = methodRegistry.createConnectionSecureBody(authResult.getChallenge()); - writeFrame(secureBody.generateFrame(0)); - } - } - - - private void disposeSaslServer() - { - SaslServer ss = getSaslServer(); - if (ss != null) - { - setSaslServer(null); - try - { - ss.dispose(); - } - catch (SaslException e) - { - _logger.error("Error disposing of Sasl server: " + e); - } - } - } - - @Override - public void receiveConnectionStartOk(final FieldTable clientProperties, - final AMQShortString mechanism, - final byte[] response, - final AMQShortString locale) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("RECV ConnectionStartOk[" - + " clientProperties: " - + clientProperties - + " mechanism: " - + mechanism - + " response: ********" - + " locale: " - + locale - + " ]"); - } - - assertState(ConnectionState.AWAIT_START_OK); - - Broker broker = getBroker(); - - _logger.info("SASL Mechanism selected: " + mechanism); - _logger.info("Locale selected: " + locale); - - SubjectCreator subjectCreator = getSubjectCreator(); - SaslServer ss; - try - { - ss = subjectCreator.createSaslServer(String.valueOf(mechanism), - getLocalFQDN(), - getPeerPrincipal()); - - if (ss == null) - { - closeConnection(AMQConstant.RESOURCE_ERROR, "Unable to create SASL Server:" + mechanism, 0); - - } - else - { - //save clientProperties - setClientProperties(clientProperties); - - setSaslServer(ss); - - final SubjectAuthenticationResult authResult = subjectCreator.authenticate(ss, response); - - MethodRegistry methodRegistry = getMethodRegistry(); - - switch (authResult.getStatus()) - { - case ERROR: - Exception cause = authResult.getCause(); - - _logger.info("Authentication failed:" + (cause == null ? "" : cause.getMessage())); - - closeConnection(AMQConstant.NOT_ALLOWED, "Authentication failed", 0); - - disposeSaslServer(); - break; - - case SUCCESS: - if (_logger.isInfoEnabled()) - { - _logger.info("Connected as: " + authResult.getSubject()); - } - setAuthorizedSubject(authResult.getSubject()); - - int frameMax = broker.getContextValue(Integer.class, Broker.BROKER_FRAME_SIZE); - - if (frameMax <= 0) - { - frameMax = Integer.MAX_VALUE; - } - - ConnectionTuneBody - tuneBody = - methodRegistry.createConnectionTuneBody(broker.getConnection_sessionCountLimit(), - frameMax, - broker.getConnection_heartBeatDelay()); - writeFrame(tuneBody.generateFrame(0)); - _state = ConnectionState.AWAIT_TUNE_OK; - break; - case CONTINUE: - ConnectionSecureBody - secureBody = methodRegistry.createConnectionSecureBody(authResult.getChallenge()); - writeFrame(secureBody.generateFrame(0)); - - _state = ConnectionState.AWAIT_SECURE_OK; - } - } - } - catch (SaslException e) - { - disposeSaslServer(); - closeConnection(AMQConstant.INTERNAL_ERROR, "SASL error: " + e, 0); - } - } - - @Override - public void receiveConnectionTuneOk(final int channelMax, final long frameMax, final int heartbeat) - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV ConnectionTuneOk[" +" channelMax: " + channelMax + " frameMax: " + frameMax + " heartbeat: " + heartbeat + " ]"); - } - - assertState(ConnectionState.AWAIT_TUNE_OK); - - initHeartbeats(heartbeat); - - int brokerFrameMax = getBroker().getContextValue(Integer.class, Broker.BROKER_FRAME_SIZE); - if (brokerFrameMax <= 0) - { - brokerFrameMax = Integer.MAX_VALUE; - } - - if (frameMax > (long) brokerFrameMax) - { - closeConnection(AMQConstant.SYNTAX_ERROR, - "Attempt to set max frame size to " + frameMax - + " greater than the broker will allow: " - + brokerFrameMax, 0); - } - else if (frameMax > 0 && frameMax < AMQConstant.FRAME_MIN_SIZE.getCode()) - { - closeConnection(AMQConstant.SYNTAX_ERROR, - "Attempt to set max frame size to " + frameMax - + " which is smaller than the specification defined minimum: " - + AMQConstant.FRAME_MIN_SIZE.getCode(), 0); - } - else - { - int calculatedFrameMax = frameMax == 0 ? brokerFrameMax : (int) frameMax; - setMaxFrameSize(calculatedFrameMax); - - //0 means no implied limit, except that forced by protocol limitations (0xFFFF) - setMaximumNumberOfChannels( ((channelMax == 0l) || (channelMax > 0xFFFFL)) - ? 0xFFFFL - : channelMax); - - } - _state = ConnectionState.AWAIT_OPEN; - - } - - public int getBinaryDataLimit() - { - return _binaryDataLimit; - } - - public long getMaxMessageSize() - { - return _maxMessageSize; - } - - public final class WriteDeliverMethod - implements ClientDeliveryMethod - { - private final int _channelId; - - public WriteDeliverMethod(int channelId) - { - _channelId = channelId; - } - - @Override - public long deliverToClient(final ConsumerImpl sub, final ServerMessage message, - final InstanceProperties props, final long deliveryTag) - { - long size = _protocolOutputConverter.writeDeliver(message, - props, - _channelId, - deliveryTag, - new AMQShortString(sub.getName())); - registerMessageDelivered(size); - return size; - } - - } - - public Object getReference() - { - return _reference; - } - - @Override - public long getLastReadTime() - { - return _lastReceivedTime; - } - - @Override - public long getLastWriteTime() - { - return _lastWriteTime; - } - - public boolean isCloseWhenNoRoute() - { - return _closeWhenNoRoute; - } - - public boolean isCompressionSupported() - { - return _compressionSupported && _broker.isMessageCompressionEnabled(); - } - - public int getMessageCompressionThreshold() - { - return _messageCompressionThreshold; - } - - public Broker getBroker() - { - return _broker; - } - - public SubjectCreator getSubjectCreator() - { - return _port.getAuthenticationProvider().getSubjectCreator(getTransport().isSecure()); - } - - public EventLogger getEventLogger() - { - if(_virtualHost != null) - { - return _virtualHost.getEventLogger(); - } - else - { - return _broker.getEventLogger(); - } - } - - @Override - public ServerChannelMethodProcessor getChannelMethodProcessor(final int channelId) - { - assertState(ConnectionState.OPEN); - - ServerChannelMethodProcessor channelMethodProcessor = getChannel(channelId); - if(channelMethodProcessor == null) - { - channelMethodProcessor = (ServerChannelMethodProcessor) Proxy.newProxyInstance(ServerMethodDispatcher.class.getClassLoader(), - new Class[] { ServerChannelMethodProcessor.class }, new InvocationHandler() - { - @Override - public Object invoke(final Object proxy, final Method method, final Object[] args) - throws Throwable - { - if(method.getName().startsWith("receive")) - { - closeConnection(AMQConstant.CHANNEL_ERROR, - "Unknown channel id: " + channelId, - channelId); - return null; - } - else if(method.getName().equals("ignoreAllButCloseOk")) - { - return false; - } - return null; - } - }); - } - return channelMethodProcessor; - } - - @Override - public void receiveHeartbeat() - { - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV Heartbeat"); - } - - // No op - } - - @Override - public void receiveProtocolHeader(final ProtocolInitiation protocolInitiation) - { - - if(_logger.isDebugEnabled()) - { - _logger.debug("RECV ProtocolHeader [" + protocolInitiation + " ]"); - } - - protocolInitiationReceived(protocolInitiation); - } - - @Override - public void setCurrentMethod(final int classId, final int methodId) - { - _currentClassId = classId; - _currentMethodId = methodId; - } - - @Override - public boolean ignoreAllButCloseOk() - { - return _closing.get(); - } - - @Override - public void processPending() - { - for (AMQSessionModel session : getSessionModels()) - { - session.processPending(); - } - - while(_asyncTaskList.peek() != null) - { - Action asyncAction = _asyncTaskList.poll(); - asyncAction.performAction(this); - } - - } - - @Override - public boolean hasWork() - { - return _stateChanged.get(); - } - - @Override - public void notifyWork() - { - _stateChanged.set(true); - - final Action listener = _workListener.get(); - if(listener != null) - { - - listener.performAction(this); - } - } - - @Override - public void clearWork() - { - _stateChanged.set(false); - } - - @Override - public void setWorkListener(final Action listener) - { - _workListener.set(listener); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/BrokerDecoder.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/BrokerDecoder.java deleted file mode 100644 index 81e0b1b736..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/BrokerDecoder.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.protocol.v0_8; - -import java.io.IOException; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; - -import javax.security.auth.Subject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.codec.MarkableDataInput; -import org.apache.qpid.codec.ServerDecoder; -import org.apache.qpid.framing.AMQFrameDecodingException; -import org.apache.qpid.server.util.ServerScopedRuntimeException; - -public class BrokerDecoder extends ServerDecoder -{ - private static final Logger _logger = LoggerFactory.getLogger(BrokerDecoder.class); - private final AMQProtocolEngine _connection; - /** - * Creates a new AMQP decoder. - * - * @param connection - */ - public BrokerDecoder(final AMQProtocolEngine connection) - { - super(connection); - _connection = connection; - } - - @Override - protected void processFrame(final int channelId, final byte type, final long bodySize, final MarkableDataInput in) - throws AMQFrameDecodingException, IOException - { - long startTime = 0; - if (_logger.isDebugEnabled()) - { - startTime = System.currentTimeMillis(); - } - Subject subject; - AMQChannel channel = _connection.getChannel(channelId); - if(channel == null) - { - subject = _connection.getSubject(); - } - else - { - _connection.channelRequiresSync(channel); - - subject = channel.getSubject(); - } - try - { - Subject.doAs(subject, new PrivilegedExceptionAction() - { - @Override - public Void run() throws IOException, AMQFrameDecodingException - { - doProcessFrame(channelId, type, bodySize, in); - return null; - } - }); - if(_logger.isDebugEnabled()) - { - _logger.debug("Frame handled in " + (System.currentTimeMillis() - startTime) + " ms."); - } - - } - catch (PrivilegedActionException e) - { - Throwable cause = e.getCause(); - if(cause instanceof IOException) - { - throw (IOException) cause; - } - else if(cause instanceof AMQFrameDecodingException) - { - throw (AMQFrameDecodingException) cause; - } - else if(cause instanceof RuntimeException) - { - throw (RuntimeException) cause; - } - else throw new ServerScopedRuntimeException(cause); - } - - } - - - private void doProcessFrame(final int channelId, final byte type, final long bodySize, final MarkableDataInput in) - throws AMQFrameDecodingException, IOException - { - super.processFrame(channelId, type, bodySize, in); - - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ClientDeliveryMethod.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ClientDeliveryMethod.java deleted file mode 100644 index c7871e8b9a..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ClientDeliveryMethod.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.protocol.v0_8; - -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.ServerMessage; - -public interface ClientDeliveryMethod -{ - long deliverToClient(final ConsumerImpl sub, final ServerMessage message, final InstanceProperties props, - final long deliveryTag); -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ConsumerTagInUseException.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ConsumerTagInUseException.java deleted file mode 100644 index 25c1462060..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ConsumerTagInUseException.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.protocol.v0_8; - -public class ConsumerTagInUseException extends Exception -{ - public ConsumerTagInUseException(final String message) - { - super(message); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ConsumerTarget_0_8.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ConsumerTarget_0_8.java deleted file mode 100644 index d46ed719b2..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ConsumerTarget_0_8.java +++ /dev/null @@ -1,565 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.v0_8; - -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; - -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.server.consumer.AbstractConsumerTarget; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.flow.FlowCreditManager; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.queue.QueueEntry; -import org.apache.qpid.server.txn.AutoCommitTransaction; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.util.StateChangeListener; - -/** - * Encapsulation of a subscription to a queue. - *

- * Ties together the protocol session of a subscriber, the consumer tag - * that was given out by the broker and the channel id. - */ -public abstract class ConsumerTarget_0_8 extends AbstractConsumerTarget implements FlowCreditManager.FlowCreditManagerListener -{ - - private final StateChangeListener _entryReleaseListener = - new StateChangeListener() - { - @Override - public void stateChanged(final MessageInstance entry, - final MessageInstance.State oldSate, - final MessageInstance.State newState) - { - if (oldSate == QueueEntry.State.ACQUIRED && newState != QueueEntry.State.ACQUIRED) - { - restoreCredit(entry.getMessage()); - } - entry.removeStateChangeListener(this); - } - }; - - private final ClientDeliveryMethod _deliveryMethod; - private final RecordDeliveryMethod _recordMethod; - - private final AtomicLong _unacknowledgedCount = new AtomicLong(0); - private final AtomicLong _unacknowledgedBytes = new AtomicLong(0); - private final List _consumers = new CopyOnWriteArrayList<>(); - private final AtomicBoolean _needToClose = new AtomicBoolean(); - - - public static ConsumerTarget_0_8 createBrowserTarget(AMQChannel channel, - AMQShortString consumerTag, FieldTable filters, - FlowCreditManager creditManager) - { - return new BrowserConsumer(channel, consumerTag, filters, creditManager, channel.getClientDeliveryMethod(), channel.getRecordDeliveryMethod()); - } - - public static ConsumerTarget_0_8 createGetNoAckTarget(final AMQChannel channel, - final AMQShortString consumerTag, - final FieldTable filters, - final FlowCreditManager creditManager, - final ClientDeliveryMethod deliveryMethod, - final RecordDeliveryMethod recordMethod) - { - return new GetNoAckConsumer(channel, consumerTag, filters, creditManager, deliveryMethod, recordMethod); - } - - public List getConsumers() - { - return _consumers; - } - - - static final class BrowserConsumer extends ConsumerTarget_0_8 - { - public BrowserConsumer(AMQChannel channel, - AMQShortString consumerTag, FieldTable filters, - FlowCreditManager creditManager, - ClientDeliveryMethod deliveryMethod, - RecordDeliveryMethod recordMethod) - { - super(channel, consumerTag, - filters, creditManager, deliveryMethod, recordMethod); - } - - /** - * 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 consumer - * @param entry - * @param batch - * @throws org.apache.qpid.AMQException - */ - @Override - public void doSend(final ConsumerImpl consumer, MessageInstance entry, boolean batch) - { - // 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(consumer, entry.getMessage(), entry.getInstanceProperties(), deliveryTag); - } - - } - - } - - public static ConsumerTarget_0_8 createNoAckTarget(AMQChannel channel, - AMQShortString consumerTag, FieldTable filters, - FlowCreditManager creditManager) - { - return new NoAckConsumer(channel, consumerTag, filters, creditManager, channel.getClientDeliveryMethod(), channel.getRecordDeliveryMethod()); - } - - public static ConsumerTarget_0_8 createNoAckTarget(AMQChannel channel, - AMQShortString consumerTag, FieldTable filters, - FlowCreditManager creditManager, - ClientDeliveryMethod deliveryMethod, - RecordDeliveryMethod recordMethod) throws AMQException - { - return new NoAckConsumer(channel, consumerTag, filters, creditManager, deliveryMethod, recordMethod); - } - - public static class NoAckConsumer extends ConsumerTarget_0_8 - { - private final AutoCommitTransaction _txn; - - public NoAckConsumer(AMQChannel channel, - AMQShortString consumerTag, FieldTable filters, - FlowCreditManager creditManager, - ClientDeliveryMethod deliveryMethod, - RecordDeliveryMethod recordMethod) - { - super(channel, consumerTag, filters, creditManager, deliveryMethod, recordMethod); - - _txn = new AutoCommitTransaction(channel.getVirtualHost().getMessageStore()); - } - - /** - * 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 consumer - * @param entry The message to send - * @param batch - */ - @Override - public void doSend(final ConsumerImpl consumer, MessageInstance entry, boolean batch) - { - // 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. - _txn.dequeue(entry.getEnqueueRecord(), NOOP); - - ServerMessage message = entry.getMessage(); - MessageReference ref = message.newReference(); - InstanceProperties props = entry.getInstanceProperties(); - entry.delete(); - long size; - synchronized (getChannel()) - { - getChannel().getConnection().setDeferFlush(batch); - long deliveryTag = getChannel().getNextDeliveryTag(); - - size = sendToClient(consumer, message, props, deliveryTag); - - } - ref.release(); - - } - - private static final ServerTransaction.Action NOOP = - new ServerTransaction.Action() - { - @Override - public void postCommit() - { - } - - @Override - public void onRollback() - { - } - }; - } - - /** - * NoAck Subscription for use with BasicGet method. - */ - public static final class GetNoAckConsumer extends NoAckConsumer - { - public GetNoAckConsumer(AMQChannel channel, - AMQShortString consumerTag, FieldTable filters, - FlowCreditManager creditManager, - ClientDeliveryMethod deliveryMethod, - RecordDeliveryMethod recordMethod) - { - super(channel, consumerTag, filters, creditManager, deliveryMethod, recordMethod); - } - - } - - - public static ConsumerTarget_0_8 createAckTarget(AMQChannel channel, - AMQShortString consumerTag, FieldTable filters, - FlowCreditManager creditManager) - { - return new AckConsumer(channel,consumerTag,filters,creditManager, channel.getClientDeliveryMethod(), channel.getRecordDeliveryMethod()); - } - - - public static ConsumerTarget_0_8 createAckTarget(AMQChannel channel, - AMQShortString consumerTag, FieldTable filters, - FlowCreditManager creditManager, - ClientDeliveryMethod deliveryMethod, - RecordDeliveryMethod recordMethod) - { - return new AckConsumer(channel,consumerTag,filters,creditManager, deliveryMethod, recordMethod); - } - - static final class AckConsumer extends ConsumerTarget_0_8 - { - public AckConsumer(AMQChannel channel, - AMQShortString consumerTag, FieldTable filters, - FlowCreditManager creditManager, - ClientDeliveryMethod deliveryMethod, - RecordDeliveryMethod recordMethod) - { - super(channel, consumerTag, filters, creditManager, deliveryMethod, recordMethod); - } - - /** - * 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 consumer - * @param entry The message to send - * @param batch - */ - @Override - public void doSend(final ConsumerImpl consumer, MessageInstance entry, boolean batch) - { - - // put queue entry on a list and then notify the connection to read list. - - synchronized (getChannel()) - { - getChannel().getConnection().setDeferFlush(batch); - long deliveryTag = getChannel().getNextDeliveryTag(); - - addUnacknowledgedMessage(entry); - recordMessageDelivery(consumer, entry, deliveryTag); - entry.addStateChangeListener(getReleasedStateChangeListener()); - long size = sendToClient(consumer, entry.getMessage(), entry.getInstanceProperties(), deliveryTag); - entry.incrementDeliveryCount(); - } - - - } - - - - - - } - - private final AMQChannel _channel; - - private final AMQShortString _consumerTag; - - private final FlowCreditManager _creditManager; - - private final Boolean _autoClose; - - private final AtomicBoolean _deleted = new AtomicBoolean(false); - - - - - public ConsumerTarget_0_8(AMQChannel channel, - AMQShortString consumerTag, - FieldTable arguments, - FlowCreditManager creditManager, - ClientDeliveryMethod deliveryMethod, - RecordDeliveryMethod recordMethod) - { - super(State.ACTIVE); - - _channel = channel; - _consumerTag = consumerTag; - - _creditManager = creditManager; - creditManager.addStateListener(this); - - _deliveryMethod = deliveryMethod; - _recordMethod = recordMethod; - - if (arguments != null) - { - Object autoClose = arguments.get(AMQPFilterTypes.AUTO_CLOSE.getValue()); - if (autoClose != null) - { - _autoClose = (Boolean) autoClose; - } - else - { - _autoClose = false; - } - } - else - { - _autoClose = false; - } - } - - @Override - public void consumerRemoved(final ConsumerImpl sub) - { - _consumers.remove(sub); - if(_consumers.isEmpty()) - { - close(); - } - } - - @Override - public void consumerAdded(final ConsumerImpl sub) - { - _consumers.add( sub ); - } - - public AMQSessionModel getSessionModel() - { - return _channel; - } - - public String toString() - { - String subscriber = "[channel=" + _channel + - ", consumerTag=" + _consumerTag + - ", session=" + getConnection().getRemoteAddressString(); - - return subscriber + "]"; - } - - @Override - public boolean doIsSuspended() - { - return getState()!=State.ACTIVE || _channel.isSuspended() || _deleted.get() || _channel.getConnectionModel().isStopped(); - } - - /** - * Callback indicating that a queue has been deleted. - * - */ - public void queueDeleted() - { - _deleted.set(true); - } - - public boolean isAutoClose() - { - return _autoClose; - } - - public FlowCreditManager getCreditManager() - { - return _creditManager; - } - - - public boolean close() - { - boolean closed = false; - State state = getState(); - - getSendLock(); - - try - { - while(!closed && state != State.CLOSED) - { - closed = updateState(state, State.CLOSED); - if(!closed) - { - state = getState(); - } - } - _creditManager.removeListener(this); - return closed; - } - finally - { - releaseSendLock(); - } - } - - - public boolean allocateCredit(ServerMessage msg) - { - return _creditManager.useCreditForMessage(msg.getSize()); - } - - public AMQChannel getChannel() - { - return _channel; - } - - public AMQShortString getConsumerTag() - { - return _consumerTag; - } - - private AMQProtocolEngine getConnection() - { - return _channel.getConnection(); - } - - public void restoreCredit(final ServerMessage message) - { - _creditManager.restoreCredit(1, message.getSize()); - } - - protected final StateChangeListener getReleasedStateChangeListener() - { - return _entryReleaseListener; - } - - public void creditStateChanged(boolean hasCredit) - { - - if(hasCredit) - { - if(!updateState(State.SUSPENDED, State.ACTIVE)) - { - // this is a hack to get round the issue of increasing bytes credit - notifyCurrentState(); - } - } - else - { - updateState(State.ACTIVE, State.SUSPENDED); - } - } - - protected long sendToClient(final ConsumerImpl consumer, final ServerMessage message, - final InstanceProperties props, - final long deliveryTag) - { - return _deliveryMethod.deliverToClient(consumer, message, props, deliveryTag); - - } - - - protected void recordMessageDelivery(final ConsumerImpl consumer, - final MessageInstance entry, - final long deliveryTag) - { - _recordMethod.recordMessageDelivery(consumer, entry, deliveryTag); - } - - - public void confirmAutoClose() - { - ProtocolOutputConverter converter = getChannel().getConnection().getProtocolOutputConverter(); - converter.confirmConsumerAutoClose(getChannel().getChannelId(), getConsumerTag()); - } - - public void queueEmpty() - { - if (isAutoClose()) - { - _needToClose.set(true); - getChannel().getConnection().notifyWork(); - } - } - - @Override - protected void processClosed() - { - if (_needToClose.get() && getState() != State.CLOSED) - { - close(); - confirmAutoClose(); - } - } - - public void flushBatched() - { - _channel.getConnection().setDeferFlush(false); - } - - protected void addUnacknowledgedMessage(MessageInstance entry) - { - final long size = entry.getMessage().getSize(); - _unacknowledgedBytes.addAndGet(size); - _unacknowledgedCount.incrementAndGet(); - entry.addStateChangeListener(new StateChangeListener() - { - public void stateChanged(MessageInstance entry, MessageInstance.State oldState, MessageInstance.State newState) - { - if(oldState.equals(MessageInstance.State.ACQUIRED) && !newState.equals(MessageInstance.State.ACQUIRED)) - { - _unacknowledgedBytes.addAndGet(-size); - _unacknowledgedCount.decrementAndGet(); - entry.removeStateChangeListener(this); - } - } - }); - } - - @Override - public void acquisitionRemoved(final MessageInstance node) - { - } - - public long getUnacknowledgedBytes() - { - return _unacknowledgedBytes.longValue(); - } - - public long getUnacknowledgedMessages() - { - return _unacknowledgedCount.longValue(); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ExtractResendAndRequeue.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ExtractResendAndRequeue.java deleted file mode 100644 index 45ab62ee05..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ExtractResendAndRequeue.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.v0_8; - -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.MessageInstance; - -public class ExtractResendAndRequeue implements UnacknowledgedMessageMap.Visitor -{ - private static final Logger _log = LoggerFactory.getLogger(ExtractResendAndRequeue.class); - - private final Map _msgToRequeue; - private final Map _msgToResend; - private final UnacknowledgedMessageMap _unacknowledgedMessageMap; - - public ExtractResendAndRequeue(UnacknowledgedMessageMap unacknowledgedMessageMap, - Map msgToRequeue, - Map msgToResend) - { - _unacknowledgedMessageMap = unacknowledgedMessageMap; - _msgToRequeue = msgToRequeue; - _msgToResend = msgToResend; - } - - public boolean callback(final long deliveryTag, MessageInstance message) - { - - message.setRedelivered(); - final ConsumerImpl consumer = message.getDeliveredConsumer(); - if (consumer != null) - { - // Consumer exists - if (!consumer.isClosed()) - { - _msgToResend.put(deliveryTag, message); - } - else // consumer has gone - { - _msgToRequeue.put(deliveryTag, message); - } - } - else - { - _log.info("No DeadLetter Queue and requeue not requested so dropping message:" + message); - } - - // false means continue processing - return false; - } - - public void visitComplete() - { - _unacknowledgedMessageMap.clear(); - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/IncomingMessage.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/IncomingMessage.java deleted file mode 100644 index 6e622fb59a..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/IncomingMessage.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.protocol.v0_8; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ContentBody; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.server.message.MessageDestination; - -public class IncomingMessage -{ - - private final MessagePublishInfo _messagePublishInfo; - private ContentHeaderBody _contentHeaderBody; - private MessageDestination _messageDestination; - - /** - * Keeps a track of how many bytes we have received in body frames - */ - private long _bodyLengthReceived = 0; - private List _contentChunks = new ArrayList(); - - public IncomingMessage(MessagePublishInfo info) - { - _messagePublishInfo = info; - } - - public void setContentHeaderBody(final ContentHeaderBody contentHeaderBody) - { - _contentHeaderBody = contentHeaderBody; - } - - public MessagePublishInfo getMessagePublishInfo() - { - return _messagePublishInfo; - } - - public long addContentBodyFrame(final ContentBody contentChunk) - { - _bodyLengthReceived += contentChunk.getSize(); - _contentChunks.add(contentChunk); - return _bodyLengthReceived; - } - - public boolean allContentReceived() - { - return (_bodyLengthReceived == getContentHeader().getBodySize()); - } - - public AMQShortString getExchangeName() - { - return _messagePublishInfo.getExchange(); - } - - public MessageDestination getDestination() - { - return _messageDestination; - } - - public ContentHeaderBody getContentHeader() - { - return _contentHeaderBody; - } - - public long getSize() - { - return getContentHeader().getBodySize(); - } - - public void setMessageDestination(final MessageDestination e) - { - _messageDestination = e; - } - - public int getBodyCount() - { - return _contentChunks.size(); - } - - public ContentBody getContentChunk(int index) - { - return _contentChunks.get(index); - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_Internal_to_v0_8.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_Internal_to_v0_8.java deleted file mode 100644 index ef42a1311f..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_Internal_to_v0_8.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.protocol.v0_8; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -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.MessagePublishInfo; -import org.apache.qpid.server.message.internal.InternalMessage; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.codec.BBEncoder; - -@PluggableService -public class MessageConverter_Internal_to_v0_8 implements MessageConverter -{ - private static final int BASIC_CLASS_ID = 60; - private static final Charset UTF_8 = Charset.forName("UTF-8"); - - - public Class getInputClass() - { - return InternalMessage.class; - } - - @Override - public Class getOutputClass() - { - return AMQMessage.class; - } - - @Override - public AMQMessage convert(InternalMessage serverMsg, VirtualHostImpl vhost) - { - return new AMQMessage(convertToStoredMessage(serverMsg), null); - } - - private StoredMessage convertToStoredMessage(final InternalMessage serverMsg) - { - final byte[] messageContent = convertToBody(serverMsg.getMessageBody()); - final MessageMetaData messageMetaData_0_8 = convertMetaData(serverMsg, - getBodyMimeType(serverMsg.getMessageBody()), - messageContent.length); - - return new StoredMessage() - { - @Override - public MessageMetaData getMetaData() - { - return messageMetaData_0_8; - } - - @Override - public long getMessageNumber() - { - return serverMsg.getMessageNumber(); - } - - @Override - public int getContent(int offsetInMessage, ByteBuffer dst) - { - int size = messageContent.length - offsetInMessage; - if(dst.remaining() < size) - { - size = dst.remaining(); - } - ByteBuffer buf = ByteBuffer.wrap(messageContent, offsetInMessage, size); - dst.put(buf); - return size; - } - - @Override - public ByteBuffer getContent(int offsetInMessage, int size) - { - return ByteBuffer.wrap(messageContent, offsetInMessage, size); - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isInMemory() - { - return true; - } - - @Override - public boolean flowToDisk() - { - return false; - } - }; - } - - private MessageMetaData convertMetaData(final InternalMessage serverMsg, final String bodyMimeType, final int size) - { - - MessagePublishInfo publishInfo = new MessagePublishInfo(AMQShortString.EMPTY_STRING, - false, - false, - AMQShortString.valueOf(serverMsg.getInitialRoutingAddress())); - - - final BasicContentHeaderProperties props = new BasicContentHeaderProperties(); - props.setAppId(serverMsg.getMessageHeader().getAppId()); - props.setContentType(bodyMimeType); - props.setCorrelationId(serverMsg.getMessageHeader().getCorrelationId()); - props.setDeliveryMode(serverMsg.isPersistent() ? BasicContentHeaderProperties.PERSISTENT : BasicContentHeaderProperties.NON_PERSISTENT); - props.setExpiration(serverMsg.getExpiration()); - props.setMessageId(serverMsg.getMessageHeader().getMessageId()); - props.setPriority(serverMsg.getMessageHeader().getPriority()); - props.setReplyTo(serverMsg.getMessageHeader().getReplyTo()); - props.setTimestamp(serverMsg.getMessageHeader().getTimestamp()); - props.setUserId(serverMsg.getMessageHeader().getUserId()); - - - Map headerProps = new LinkedHashMap(); - - for(String headerName : serverMsg.getMessageHeader().getHeaderNames()) - { - headerProps.put(headerName, serverMsg.getMessageHeader().getHeader(headerName)); - } - - props.setHeaders(FieldTable.convertToFieldTable(headerProps)); - - final ContentHeaderBody chb = new ContentHeaderBody(props); - chb.setBodySize(size); - return new MessageMetaData(publishInfo, chb, serverMsg.getArrivalTime()); - } - - - @Override - public String getType() - { - return "Internal to v0-8"; - } - - - public static byte[] convertToBody(Object object) - { - if(object instanceof String) - { - return ((String)object).getBytes(UTF_8); - } - else if(object instanceof byte[]) - { - return (byte[]) object; - } - else if(object instanceof Map) - { - BBEncoder encoder = new BBEncoder(1024); - encoder.writeMap((Map)object); - ByteBuffer buf = encoder.segment(); - int remaining = buf.remaining(); - byte[] data = new byte[remaining]; - buf.get(data); - return data; - - } - else if(object instanceof List) - { - BBEncoder encoder = new BBEncoder(1024); - encoder.writeList((List) object); - ByteBuffer buf = encoder.segment(); - int remaining = buf.remaining(); - byte[] data = new byte[remaining]; - buf.get(data); - return data; - } - else - { - ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); - try - { - ObjectOutputStream os = new ObjectOutputStream(bytesOut); - os.writeObject(object); - return bytesOut.toByteArray(); - } - catch (IOException e) - { - throw new ConnectionScopedRuntimeException(e); - } - } - } - - public static String getBodyMimeType(Object object) - { - if(object instanceof String) - { - return "text/plain"; - } - else if(object instanceof byte[]) - { - return "application/octet-stream"; - } - else if(object instanceof Map) - { - return "amqp/map"; - } - else if(object instanceof List) - { - return "amqp/list"; - } - else - { - return "application/java-object-stream"; - } - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_v0_8_to_Internal.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_v0_8_to_Internal.java deleted file mode 100644 index 0b98699b4a..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_v0_8_to_Internal.java +++ /dev/null @@ -1,358 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.v0_8; - -import java.io.EOFException; -import java.net.URISyntaxException; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.internal.InternalMessage; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.codec.BBDecoder; -import org.apache.qpid.typedmessage.TypedBytesContentReader; -import org.apache.qpid.typedmessage.TypedBytesFormatException; -import org.apache.qpid.url.AMQBindingURL; - -@PluggableService -public class MessageConverter_v0_8_to_Internal implements MessageConverter -{ - @Override - public Class getInputClass() - { - return AMQMessage.class; - } - - @Override - public Class getOutputClass() - { - return InternalMessage.class; - } - - @Override - public InternalMessage convert(AMQMessage serverMessage, VirtualHostImpl vhost) - { - final String mimeType = serverMessage.getMessageHeader().getMimeType(); - byte[] data = new byte[(int) serverMessage.getSize()]; - serverMessage.getContent(ByteBuffer.wrap(data), 0); - - Object body = convertMessageBody(mimeType, data); - - return InternalMessage.convert(serverMessage.getMessageNumber(), serverMessage.isPersistent(), - new DelegatingMessageHeader(serverMessage.getMessageHeader()), body); - } - - private static class ReplyToComponents - { - private String _exchange; - private String _queue; - private String _routingKey; - - public void setExchange(final String exchange) - { - _exchange = exchange; - } - - public void setQueue(final String queue) - { - _queue = queue; - } - - public void setRoutingKey(final String routingKey) - { - _routingKey = routingKey; - } - - public String getExchange() - { - return _exchange; - } - - public String getQueue() - { - return _queue; - } - - public String getRoutingKey() - { - return _routingKey; - } - - public boolean hasExchange() - { - return _exchange != null; - } - - public boolean hasQueue() - { - return _queue != null; - } - - public boolean hasRoutingKey() - { - return _routingKey != null; - } - } - - private static class DelegatingMessageHeader implements AMQMessageHeader - { - private final AMQMessageHeader _delegate; - - private DelegatingMessageHeader(final AMQMessageHeader delegate) - { - _delegate = delegate; - } - - @Override - public String getCorrelationId() - { - return _delegate.getCorrelationId(); - } - - @Override - public long getExpiration() - { - return _delegate.getExpiration(); - } - - @Override - public String getUserId() - { - return _delegate.getUserId(); - } - - @Override - public String getAppId() - { - return _delegate.getAppId(); - } - - @Override - public String getMessageId() - { - return _delegate.getMessageId(); - } - - @Override - public String getMimeType() - { - return _delegate.getMimeType(); - } - - @Override - public String getEncoding() - { - return _delegate.getEncoding(); - } - - @Override - public byte getPriority() - { - return _delegate.getPriority(); - } - - @Override - public long getTimestamp() - { - return _delegate.getTimestamp(); - } - - @Override - public String getType() - { - return _delegate.getType(); - } - - @Override - public String getReplyTo() - { - String originalReplyTo = _delegate.getReplyTo(); - ReplyToComponents replyTo = convertReplyTo(originalReplyTo); - if(replyTo != null) - { - if(replyTo.hasExchange()) - { - return replyTo.getExchange() + (replyTo.hasRoutingKey() ? "/" + replyTo.getRoutingKey() : ""); - } - else - { - return replyTo.hasQueue() ? replyTo.getQueue() : replyTo.getRoutingKey(); - } - } - else - { - return originalReplyTo; - } - } - - private ReplyToComponents convertReplyTo(final String origReplyToString) - { - try - { - AMQBindingURL burl = new AMQBindingURL(origReplyToString); - ReplyToComponents replyTo = new ReplyToComponents(); - AMQShortString routingKey = burl.getRoutingKey(); - if(routingKey != null) - { - replyTo.setRoutingKey(routingKey.asString()); - } - - AMQShortString exchangeName = burl.getExchangeName(); - if(exchangeName != null) - { - replyTo.setExchange(exchangeName.asString()); - } - - AMQShortString queueName = burl.getQueueName(); - if(queueName != null) - { - replyTo.setQueue(queueName.asString()); - } - return replyTo; - } - catch (URISyntaxException e) - { - return null; - } - } - - @Override - public Object getHeader(final String name) - { - return _delegate.getHeader(name); - } - - @Override - public boolean containsHeaders(final Set names) - { - return _delegate.containsHeaders(names); - } - - @Override - public boolean containsHeader(final String name) - { - return _delegate.containsHeader(name); - } - - @Override - public Collection getHeaderNames() - { - return _delegate.getHeaderNames(); - } - } - - - private static Object convertMessageBody(String mimeType, byte[] data) - { - if("text/plain".equals(mimeType) || "text/xml".equals(mimeType)) - { - String text = new String(data); - return text; - } - else if("jms/map-message".equals(mimeType)) - { - TypedBytesContentReader reader = new TypedBytesContentReader(ByteBuffer.wrap(data)); - - LinkedHashMap map = new LinkedHashMap(); - final int entries = reader.readIntImpl(); - for (int i = 0; i < entries; i++) - { - try - { - String propName = reader.readStringImpl(); - Object value = reader.readObject(); - - map.put(propName, value); - } - catch (EOFException e) - { - throw new IllegalArgumentException(e); - } - catch (TypedBytesFormatException e) - { - throw new IllegalArgumentException(e); - } - - } - - return map; - - } - else if("amqp/map".equals(mimeType)) - { - BBDecoder decoder = new BBDecoder(); - decoder.init(ByteBuffer.wrap(data)); - final Map map = decoder.readMap(); - - return map; - - } - else if("amqp/list".equals(mimeType)) - { - BBDecoder decoder = new BBDecoder(); - decoder.init(ByteBuffer.wrap(data)); - return decoder.readList(); - } - else if("jms/stream-message".equals(mimeType)) - { - TypedBytesContentReader reader = new TypedBytesContentReader(ByteBuffer.wrap(data)); - - List list = new ArrayList(); - while (reader.remaining() != 0) - { - try - { - list.add(reader.readObject()); - } - catch (TypedBytesFormatException e) - { - throw new ConnectionScopedRuntimeException(e); - } - catch (EOFException e) - { - throw new ConnectionScopedRuntimeException(e); - } - } - return list; - } - else - { - return data; - - } - } - - @Override - public String getType() - { - return "v0-8 to Internal"; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaData.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaData.java deleted file mode 100644 index 6b2902d0fa..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaData.java +++ /dev/null @@ -1,296 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.v0_8; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.Collection; -import java.util.Set; - -import org.apache.qpid.framing.AMQFrameDecodingException; -import org.apache.qpid.framing.AMQProtocolVersionException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.EncodingUtils; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.plugin.MessageMetaDataType; -import org.apache.qpid.server.store.StorableMessageMetaData; -import org.apache.qpid.server.util.ByteBufferOutputStream; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.util.ByteBufferInputStream; - -/** - * 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 final MessagePublishInfo _messagePublishInfo; - - private final ContentHeaderBody _contentHeaderBody; - - - private long _arrivalTime; - private static final byte MANDATORY_FLAG = 1; - private static final byte IMMEDIATE_FLAG = 2; - public static final MessageMetaDataType.Factory FACTORY = new MetaDataFactory(); - private static final MessageMetaDataType_0_8 TYPE = new MessageMetaDataType_0_8(); - - public MessageMetaData(MessagePublishInfo publishBody, ContentHeaderBody contentHeaderBody) - { - this(publishBody,contentHeaderBody, System.currentTimeMillis()); - } - - public MessageMetaData(MessagePublishInfo publishBody, - ContentHeaderBody contentHeaderBody, - long arrivalTime) - { - _contentHeaderBody = contentHeaderBody; - _messagePublishInfo = publishBody; - _arrivalTime = arrivalTime; - } - - - public ContentHeaderBody getContentHeaderBody() - { - return _contentHeaderBody; - } - - public MessagePublishInfo getMessagePublishInfo() - { - return _messagePublishInfo; - } - - public long getArrivalTime() - { - return _arrivalTime; - } - - public MessageMetaDataType getType() - { - return TYPE; - } - - 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(ByteBuffer dest) - { - int oldPosition = dest.position(); - try - { - - DataOutputStream dataOutputStream = new DataOutputStream(new ByteBufferOutputStream(dest)); - EncodingUtils.writeInteger(dataOutputStream, _contentHeaderBody.getSize()); - _contentHeaderBody.writePayload(dataOutputStream); - EncodingUtils.writeShortStringBytes(dataOutputStream, _messagePublishInfo.getExchange()); - EncodingUtils.writeShortStringBytes(dataOutputStream, _messagePublishInfo.getRoutingKey()); - byte flags = 0; - if(_messagePublishInfo.isMandatory()) - { - flags |= MANDATORY_FLAG; - } - if(_messagePublishInfo.isImmediate()) - { - flags |= IMMEDIATE_FLAG; - } - dest.put(flags); - dest.putLong(_arrivalTime); - - } - catch (IOException e) - { - // This shouldn't happen as we are not actually using anything that can throw an IO Exception - throw new ConnectionScopedRuntimeException(e); - } - - return dest.position()-oldPosition; - } - - public int getContentSize() - { - return (int) _contentHeaderBody.getBodySize(); - } - - public boolean isPersistent() - { - return _contentHeaderBody.getProperties().getDeliveryMode() == BasicContentHeaderProperties.PERSISTENT; - } - - private static class MetaDataFactory implements MessageMetaDataType.Factory - { - - - public MessageMetaData createMetaData(ByteBuffer buf) - { - try - { - ByteBufferInputStream bbis = new ByteBufferInputStream(buf); - DataInputStream dais = new DataInputStream(bbis); - int size = EncodingUtils.readInteger(dais); - ContentHeaderBody chb = ContentHeaderBody.createFromBuffer(dais, size); - final AMQShortString exchange = EncodingUtils.readAMQShortString(dais); - final AMQShortString routingKey = EncodingUtils.readAMQShortString(dais); - - final byte flags = EncodingUtils.readByte(dais); - long arrivalTime = EncodingUtils.readLong(dais); - - MessagePublishInfo publishBody = - new MessagePublishInfo(exchange, - (flags & IMMEDIATE_FLAG) != 0, - (flags & MANDATORY_FLAG) != 0, - routingKey); - - return new MessageMetaData(publishBody, chb, arrivalTime); - } - catch (IOException e) - { - throw new ConnectionScopedRuntimeException(e); - } - catch (AMQProtocolVersionException e) - { - throw new ConnectionScopedRuntimeException(e); - } - catch (AMQFrameDecodingException e) - { - throw new ConnectionScopedRuntimeException(e); - } - - } - } - - public AMQMessageHeader getMessageHeader() - { - return new MessageHeaderAdapter(); - } - - private final class MessageHeaderAdapter implements AMQMessageHeader - { - private BasicContentHeaderProperties getProperties() - { - return getContentHeaderBody().getProperties(); - } - - public String getUserId() - { - return getProperties().getUserIdAsString(); - } - - public String getAppId() - { - return getProperties().getAppIdAsString(); - } - - 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 Object getHeader(String name) - { - FieldTable ft = getProperties().getHeaders(); - return ft.get(name); - } - - public boolean containsHeaders(Set names) - { - FieldTable ft = getProperties().getHeaders(); - for(String name : names) - { - if(!ft.containsKey(name)) - { - return false; - } - } - return true; - } - - @Override - public Collection getHeaderNames() - { - return getProperties().getHeaders().keys(); - } - - public boolean containsHeader(String name) - { - FieldTable ft = getProperties().getHeaders(); - return ft.containsKey(name); - } - - - - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaDataType_0_8.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaDataType_0_8.java deleted file mode 100644 index 5e263cd3b0..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaDataType_0_8.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.protocol.v0_8; - -import java.nio.ByteBuffer; - -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.plugin.MessageMetaDataType; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.store.StoredMessage; - -@PluggableService -public class MessageMetaDataType_0_8 implements MessageMetaDataType -{ - - public static final int TYPE = 0; - public static final String V0_8 = "v0_8"; - - @Override - public int ordinal() - { - return TYPE; - } - - @Override - public MessageMetaData createMetaData(ByteBuffer buf) - { - return MessageMetaData.FACTORY.createMetaData(buf); - } - - @Override - public ServerMessage createMessage(StoredMessage msg) - { - return new AMQMessage(msg); - } - - public int hashCode() - { - return ordinal(); - } - - public boolean equals(Object o) - { - return o != null && o.getClass() == getClass(); - } - - @Override - public String getType() - { - return V0_8; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageOnlyCreditManager.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageOnlyCreditManager.java deleted file mode 100644 index af54c911dc..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageOnlyCreditManager.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.protocol.v0_8; - -import java.util.concurrent.atomic.AtomicLong; - -import org.apache.qpid.server.flow.AbstractFlowCreditManager; -import org.apache.qpid.server.flow.FlowCreditManager; - -public class MessageOnlyCreditManager extends AbstractFlowCreditManager implements FlowCreditManager -{ - private final AtomicLong _messageCredit; - - public MessageOnlyCreditManager(final long initialCredit) - { - _messageCredit = new AtomicLong(initialCredit); - } - - public void restoreCredit(long messageCredit, long bytesCredit) - { - _messageCredit.addAndGet(messageCredit); - setSuspended(false); - - } - - public boolean hasCredit() - { - return _messageCredit.get() > 0L; - } - - public boolean useCreditForMessage(long msgSize) - { - 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/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/NoAckCreditManager.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/NoAckCreditManager.java deleted file mode 100644 index 6e5aab2dd5..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/NoAckCreditManager.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.protocol.v0_8; - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.flow.AbstractFlowCreditManager; - -public class NoAckCreditManager extends AbstractFlowCreditManager -{ - private final ServerProtocolEngine _serverProtocolEngine; - - public NoAckCreditManager(ServerProtocolEngine serverProtocolEngine) - { - _serverProtocolEngine = serverProtocolEngine; - } - - @Override - public void restoreCredit(final long messageCredit, final long bytesCredit) - { - setSuspended(!hasCredit()); - } - - @Override - public boolean hasCredit() - { - return !_serverProtocolEngine.isTransportBlockedForWriting(); - } - - @Override - public boolean useCreditForMessage(final long msgSize) - { - if (!hasCredit()) - { - setSuspended(true); - return false; - } - return true; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/Pre0_10CreditManager.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/Pre0_10CreditManager.java deleted file mode 100644 index a869a707e1..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/Pre0_10CreditManager.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.server.protocol.v0_8; - - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.flow.AbstractFlowCreditManager; -import org.apache.qpid.server.flow.FlowCreditManager; - -public class Pre0_10CreditManager extends AbstractFlowCreditManager implements FlowCreditManager -{ - - private final ServerProtocolEngine _protocolEngine; - private volatile long _bytesCreditLimit; - private volatile long _messageCreditLimit; - - private volatile long _bytesCredit; - private volatile long _messageCredit; - - public Pre0_10CreditManager(long bytesCreditLimit, - long messageCreditLimit, - ServerProtocolEngine protocolEngine) - { - _protocolEngine = protocolEngine; - _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 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 boolean hasCredit() - { - return (_bytesCreditLimit == 0L || _bytesCredit > 0) - && (_messageCreditLimit == 0L || _messageCredit > 0) - && !_protocolEngine.isTransportBlockedForWriting(); - } - - public synchronized boolean useCreditForMessage(final long msgSize) - { - if (_protocolEngine.isTransportBlockedForWriting()) - { - setSuspended(true); - return false; - } - else if(_messageCreditLimit != 0L) - { - if(_messageCredit != 0L) - { - if(_bytesCreditLimit == 0L) - { - _messageCredit--; - - return true; - } - else - { - if((_bytesCredit >= msgSize) || (_bytesCredit == _bytesCreditLimit)) - { - _messageCredit--; - _bytesCredit -= msgSize; - - return true; - } - else - { - return false; - } - } - } - else - { - setSuspended(true); - return false; - } - } - else - { - if(_bytesCreditLimit == 0L) - { - - return true; - } - else - { - if((_bytesCredit >= msgSize) || (_bytesCredit == _bytesCreditLimit)) - { - _bytesCredit -= msgSize; - - return true; - } - else - { - return false; - } - } - - } - - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolEngineCreator_0_8.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolEngineCreator_0_8.java deleted file mode 100644 index e8cf028069..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolEngineCreator_0_8.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.protocol.v0_8; - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Protocol; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.plugin.ProtocolEngineCreator; -import org.apache.qpid.transport.network.NetworkConnection; - -@PluggableService -public class ProtocolEngineCreator_0_8 implements ProtocolEngineCreator -{ - 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 - }; - - - public ProtocolEngineCreator_0_8() - { - } - - public Protocol getVersion() - { - return Protocol.AMQP_0_8; - } - - public byte[] getHeaderIdentifier() - { - return AMQP_0_8_HEADER; - } - - public ServerProtocolEngine newProtocolEngine(Broker broker, - NetworkConnection network, - AmqpPort port, - Transport transport, - long id) - { - return new AMQProtocolEngine(broker, network, id, port, transport); - } - - private static ProtocolEngineCreator INSTANCE = new ProtocolEngineCreator_0_8(); - - public static ProtocolEngineCreator getInstance() - { - return INSTANCE; - } - - @Override - public String getType() - { - return getVersion().toString(); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolEngineCreator_0_9.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolEngineCreator_0_9.java deleted file mode 100644 index 8817e79aff..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolEngineCreator_0_9.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.protocol.v0_8; - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Protocol; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.plugin.ProtocolEngineCreator; -import org.apache.qpid.transport.network.NetworkConnection; - -@PluggableService -public class ProtocolEngineCreator_0_9 implements ProtocolEngineCreator -{ - 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 - }; - - public ProtocolEngineCreator_0_9() - { - } - - public Protocol getVersion() - { - return Protocol.AMQP_0_9; - } - - - public byte[] getHeaderIdentifier() - { - return AMQP_0_9_HEADER; - } - - public ServerProtocolEngine newProtocolEngine(Broker broker, - NetworkConnection network, - AmqpPort port, - Transport transport, - long id) - { - return new AMQProtocolEngine(broker, network, id, port, transport); - } - - private static ProtocolEngineCreator INSTANCE = new ProtocolEngineCreator_0_9(); - - public static ProtocolEngineCreator getInstance() - { - return INSTANCE; - } - - @Override - public String getType() - { - return getVersion().toString(); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolEngineCreator_0_9_1.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolEngineCreator_0_9_1.java deleted file mode 100644 index af37b17d85..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolEngineCreator_0_9_1.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.protocol.v0_8; - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Protocol; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.plugin.ProtocolEngineCreator; -import org.apache.qpid.transport.network.NetworkConnection; - -@PluggableService -public class ProtocolEngineCreator_0_9_1 implements ProtocolEngineCreator -{ - - 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 - }; - - public ProtocolEngineCreator_0_9_1() - { - } - - public Protocol getVersion() - { - return Protocol.AMQP_0_9_1; - } - - - public byte[] getHeaderIdentifier() - { - return AMQP_0_9_1_HEADER; - } - - public ServerProtocolEngine newProtocolEngine(Broker broker, - NetworkConnection network, - AmqpPort port, - Transport transport, - long id) - { - return new AMQProtocolEngine(broker, network, id, port, transport); - } - - - private static ProtocolEngineCreator INSTANCE = new ProtocolEngineCreator_0_9_1(); - - public static ProtocolEngineCreator getInstance() - { - return INSTANCE; - } - - @Override - public String getType() - { - return getVersion().toString(); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolOutputConverter.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolOutputConverter.java deleted file mode 100644 index 69f71f14a9..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolOutputConverter.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. - * - */ - -/* - * This file is auto-generated by Qpid Gentools v.0.1 - do not modify. - * Supported AMQP versions: - * 8-0 - */ -package org.apache.qpid.server.protocol.v0_8; - -import org.apache.qpid.framing.AMQDataBlock; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.MessageContentSource; -import org.apache.qpid.server.message.ServerMessage; - -public interface ProtocolOutputConverter -{ - void confirmConsumerAutoClose(int channelId, AMQShortString consumerTag); - - long writeDeliver(final ServerMessage msg, - final InstanceProperties props, int channelId, - long deliveryTag, - AMQShortString consumerTag); - - long writeGetOk(final ServerMessage msg, - final InstanceProperties props, - int channelId, - long deliveryTag, - int queueSize); - - void writeReturn(MessagePublishInfo messagePublishInfo, ContentHeaderBody header, MessageContentSource msgContent, int channelId, int replyCode, AMQShortString replyText); - - void writeFrame(AMQDataBlock block); -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolOutputConverterImpl.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolOutputConverterImpl.java deleted file mode 100644 index 15ce9262fc..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolOutputConverterImpl.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.server.protocol.v0_8; - -import java.io.DataOutput; -import java.io.IOException; -import java.nio.ByteBuffer; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQBody; -import org.apache.qpid.framing.AMQDataBlock; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.AMQMethodBody; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicCancelOkBody; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.BasicGetOkBody; -import org.apache.qpid.framing.BasicReturnBody; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.protocol.AMQVersionAwareProtocolSession; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.MessageContentSource; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.protocol.MessageConverterRegistry; -import org.apache.qpid.transport.ByteBufferSender; -import org.apache.qpid.util.GZIPUtils; - -public class ProtocolOutputConverterImpl implements ProtocolOutputConverter -{ - private static final int BASIC_CLASS_ID = 60; - - private final AMQProtocolEngine _connection; - private static final AMQShortString GZIP_ENCODING = AMQShortString.valueOf(GZIPUtils.GZIP_CONTENT_ENCODING); - - public ProtocolOutputConverterImpl(AMQProtocolEngine connection) - { - _connection = connection; - } - - - public long writeDeliver(final ServerMessage m, - final InstanceProperties props, int channelId, - long deliveryTag, - AMQShortString consumerTag) - { - final AMQMessage msg = convertToAMQMessage(m); - final boolean isRedelivered = Boolean.TRUE.equals(props.getProperty(InstanceProperties.Property.REDELIVERED)); - AMQBody deliverBody = createEncodedDeliverBody(msg, isRedelivered, deliveryTag, consumerTag); - return writeMessageDelivery(msg, channelId, deliverBody); - } - - private AMQMessage convertToAMQMessage(ServerMessage serverMessage) - { - if(serverMessage instanceof AMQMessage) - { - return (AMQMessage) serverMessage; - } - else - { - return getMessageConverter(serverMessage).convert(serverMessage, _connection.getVirtualHost()); - } - } - - private MessageConverter getMessageConverter(M message) - { - Class clazz = (Class) message.getClass(); - return MessageConverterRegistry.getConverter(clazz, AMQMessage.class); - } - - private long writeMessageDelivery(AMQMessage message, int channelId, AMQBody deliverBody) - { - return writeMessageDelivery(message, message.getContentHeaderBody(), channelId, deliverBody); - } - - private long writeMessageDelivery(MessageContentSource message, ContentHeaderBody contentHeaderBody, int channelId, AMQBody deliverBody) - { - - int bodySize = (int) message.getSize(); - boolean msgCompressed = isCompressed(contentHeaderBody); - byte[] modifiedContent; - - // straight through case - boolean compressionSupported = _connection.isCompressionSupported(); - - if(msgCompressed && !compressionSupported && - (modifiedContent = GZIPUtils.uncompressBufferToArray(message.getContent(0,bodySize))) != null) - { - BasicContentHeaderProperties modifiedProps = - new BasicContentHeaderProperties(contentHeaderBody.getProperties()); - modifiedProps.setEncoding((String)null); - - writeMessageDeliveryModified(channelId, deliverBody, modifiedProps, modifiedContent); - - return modifiedContent.length; - } - else if(!msgCompressed - && compressionSupported - && contentHeaderBody.getProperties().getEncoding()==null - && bodySize > _connection.getMessageCompressionThreshold() - && (modifiedContent = GZIPUtils.compressBufferToArray(message.getContent(0, bodySize))) != null) - { - BasicContentHeaderProperties modifiedProps = - new BasicContentHeaderProperties(contentHeaderBody.getProperties()); - modifiedProps.setEncoding(GZIP_ENCODING); - - writeMessageDeliveryModified(channelId, deliverBody, modifiedProps, modifiedContent); - - return modifiedContent.length; - } - else - { - writeMessageDeliveryUnchanged(message, contentHeaderBody, channelId, deliverBody, bodySize); - - return bodySize; - } - } - - private int writeMessageDeliveryModified(final int channelId, - final AMQBody deliverBody, - final BasicContentHeaderProperties modifiedProps, - final byte[] content) - { - final int bodySize; - bodySize = content.length; - ContentHeaderBody modifiedHeaderBody = - new ContentHeaderBody(modifiedProps, bodySize); - final MessageContentSource wrappedSource = new MessageContentSource() - { - @Override - public int getContent(final ByteBuffer buf, final int offset) - { - int size = Math.min(buf.remaining(), content.length - offset); - buf.put(content, offset, size); - return size; - } - - @Override - public ByteBuffer getContent(final int offset, final int size) - { - return ByteBuffer.wrap(content, offset, size); - } - - @Override - public long getSize() - { - return content.length; - } - }; - writeMessageDeliveryUnchanged(wrappedSource, modifiedHeaderBody, channelId, deliverBody, bodySize); - return bodySize; - } - - private void writeMessageDeliveryUnchanged(final MessageContentSource message, - final ContentHeaderBody contentHeaderBody, - final int channelId, final AMQBody deliverBody, final int bodySize) - { - if (bodySize == 0) - { - SmallCompositeAMQBodyBlock compositeBlock = new SmallCompositeAMQBodyBlock(channelId, deliverBody, - contentHeaderBody); - - writeFrame(compositeBlock); - } - else - { - int maxBodySize = (int) _connection.getMaxFrameSize() - AMQFrame.getFrameOverhead(); - - - int capacity = bodySize > maxBodySize ? maxBodySize : bodySize; - - int writtenSize = capacity; - - AMQBody firstContentBody = new MessageContentSourceBody(message, 0, capacity); - - CompositeAMQBodyBlock - compositeBlock = - new CompositeAMQBodyBlock(channelId, deliverBody, contentHeaderBody, firstContentBody); - writeFrame(compositeBlock); - - while (writtenSize < bodySize) - { - capacity = bodySize - writtenSize > maxBodySize ? maxBodySize : bodySize - writtenSize; - MessageContentSourceBody body = new MessageContentSourceBody(message, writtenSize, capacity); - writtenSize += capacity; - - writeFrame(new AMQFrame(channelId, body)); - } - } - } - - private boolean isCompressed(final ContentHeaderBody contentHeaderBody) - { - return GZIP_ENCODING.equals(contentHeaderBody.getProperties().getEncoding()); - } - - private class MessageContentSourceBody implements AMQBody - { - public static final byte TYPE = 3; - private final int _length; - private final MessageContentSource _message; - private final int _offset; - - public MessageContentSourceBody(MessageContentSource message, int offset, int length) - { - _message = message; - _offset = offset; - _length = length; - } - - public byte getFrameType() - { - return TYPE; - } - - public int getSize() - { - return _length; - } - - public void writePayload(DataOutput buffer) throws IOException - { - ByteBuffer buf = _message.getContent(_offset, _length); - - if(buf.hasArray()) - { - buffer.write(buf.array(), buf.arrayOffset()+buf.position(), buf.remaining()); - } - else - { - - byte[] data = new byte[_length]; - - buf.get(data); - - buffer.write(data); - } - } - - @Override - public long writePayload(final ByteBufferSender sender) throws IOException - { - ByteBuffer buf = _message.getContent(_offset, _length); - long size = buf.remaining(); - sender.send(buf.duplicate()); - return size; - } - - public void handle(int channelId, AMQVersionAwareProtocolSession amqProtocolSession) throws AMQException - { - throw new UnsupportedOperationException(); - } - - @Override - public String toString() - { - return "[" + getClass().getSimpleName() + " offset: " + _offset + ", length: " + _length + "]"; - } - - } - - public long writeGetOk(final ServerMessage msg, - final InstanceProperties props, - int channelId, - long deliveryTag, - int queueSize) - { - AMQBody deliver = createEncodedGetOkBody(msg, props, deliveryTag, queueSize); - return writeMessageDelivery(convertToAMQMessage(msg), channelId, deliver); - } - - - private AMQBody createEncodedDeliverBody(AMQMessage message, - boolean isRedelivered, - final long deliveryTag, - final AMQShortString consumerTag) - { - - final AMQShortString exchangeName; - final AMQShortString routingKey; - - final MessagePublishInfo pb = message.getMessagePublishInfo(); - exchangeName = pb.getExchange(); - routingKey = pb.getRoutingKey(); - - final AMQBody returnBlock = new EncodedDeliveryBody(deliveryTag, routingKey, exchangeName, consumerTag, isRedelivered); - return returnBlock; - } - - private class EncodedDeliveryBody implements AMQBody - { - private final long _deliveryTag; - private final AMQShortString _routingKey; - private final AMQShortString _exchangeName; - private final AMQShortString _consumerTag; - private final boolean _isRedelivered; - private AMQBody _underlyingBody; - - private EncodedDeliveryBody(long deliveryTag, AMQShortString routingKey, AMQShortString exchangeName, AMQShortString consumerTag, boolean isRedelivered) - { - _deliveryTag = deliveryTag; - _routingKey = routingKey; - _exchangeName = exchangeName; - _consumerTag = consumerTag; - _isRedelivered = isRedelivered; - } - - public AMQBody createAMQBody() - { - return _connection.getMethodRegistry().createBasicDeliverBody(_consumerTag, - _deliveryTag, - _isRedelivered, - _exchangeName, - _routingKey); - } - - public byte getFrameType() - { - return AMQMethodBody.TYPE; - } - - public int getSize() - { - if(_underlyingBody == null) - { - _underlyingBody = createAMQBody(); - } - return _underlyingBody.getSize(); - } - - public void writePayload(DataOutput buffer) throws IOException - { - if(_underlyingBody == null) - { - _underlyingBody = createAMQBody(); - } - _underlyingBody.writePayload(buffer); - } - - public long writePayload(ByteBufferSender sender) throws IOException - { - if(_underlyingBody == null) - { - _underlyingBody = createAMQBody(); - } - return _underlyingBody.writePayload(sender); - } - - public void handle(final int channelId, final AMQVersionAwareProtocolSession amqProtocolSession) - throws AMQException - { - throw new AMQException("This block should never be dispatched!"); - } - - @Override - public String toString() - { - return "[" + getClass().getSimpleName() + " underlyingBody: " + String.valueOf(_underlyingBody) + "]"; - } - } - - private AMQBody createEncodedGetOkBody(ServerMessage msg, InstanceProperties props, long deliveryTag, int queueSize) - { - final AMQShortString exchangeName; - final AMQShortString routingKey; - - final AMQMessage message = convertToAMQMessage(msg); - final MessagePublishInfo pb = message.getMessagePublishInfo(); - exchangeName = pb.getExchange(); - routingKey = pb.getRoutingKey(); - - final boolean isRedelivered = Boolean.TRUE.equals(props.getProperty(InstanceProperties.Property.REDELIVERED)); - - BasicGetOkBody getOkBody = - _connection.getMethodRegistry().createBasicGetOkBody(deliveryTag, - isRedelivered, - exchangeName, - routingKey, - queueSize); - - return getOkBody; - } - - private AMQBody createEncodedReturnFrame(MessagePublishInfo messagePublishInfo, - int replyCode, - AMQShortString replyText) - { - - BasicReturnBody basicReturnBody = - _connection.getMethodRegistry().createBasicReturnBody(replyCode, - replyText, - messagePublishInfo.getExchange(), - messagePublishInfo.getRoutingKey()); - - - return basicReturnBody; - } - - public void writeReturn(MessagePublishInfo messagePublishInfo, ContentHeaderBody header, MessageContentSource message, int channelId, int replyCode, AMQShortString replyText) - { - - AMQBody returnFrame = createEncodedReturnFrame(messagePublishInfo, replyCode, replyText); - - writeMessageDelivery(message, header, channelId, returnFrame); - } - - - public void writeFrame(AMQDataBlock block) - { - _connection.writeFrame(block); - } - - - public void confirmConsumerAutoClose(int channelId, AMQShortString consumerTag) - { - - BasicCancelOkBody basicCancelOkBody = _connection.getMethodRegistry().createBasicCancelOkBody(consumerTag); - writeFrame(basicCancelOkBody.generateFrame(channelId)); - - } - - - public static final class CompositeAMQBodyBlock extends AMQDataBlock - { - public static final int OVERHEAD = 3 * AMQFrame.getFrameOverhead(); - - private final AMQBody _methodBody; - private final AMQBody _headerBody; - private final AMQBody _contentBody; - private final int _channel; - - - public CompositeAMQBodyBlock(int channel, AMQBody methodBody, AMQBody headerBody, AMQBody contentBody) - { - _channel = channel; - _methodBody = methodBody; - _headerBody = headerBody; - _contentBody = contentBody; - } - - public long getSize() - { - return OVERHEAD + _methodBody.getSize() + _headerBody.getSize() + _contentBody.getSize(); - } - - public void writePayload(DataOutput buffer) throws IOException - { - AMQFrame.writeFrames(buffer, _channel, _methodBody, _headerBody, _contentBody); - } - - @Override - public long writePayload(final ByteBufferSender sender) throws IOException - { - long size = (new AMQFrame(_channel, _methodBody)).writePayload(sender); - - size += (new AMQFrame(_channel, _headerBody)).writePayload(sender); - - size += (new AMQFrame(_channel, _contentBody)).writePayload(sender); - - return size; - } - - @Override - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[").append(getClass().getSimpleName()) - .append(" methodBody=").append(_methodBody) - .append(", headerBody=").append(_headerBody) - .append(", contentBody=").append(_contentBody) - .append(", channel=").append(_channel).append("]"); - return builder.toString(); - } - - } - - public static final class SmallCompositeAMQBodyBlock extends AMQDataBlock - { - public static final int OVERHEAD = 2 * AMQFrame.getFrameOverhead(); - - private final AMQBody _methodBody; - private final AMQBody _headerBody; - private final int _channel; - - - public SmallCompositeAMQBodyBlock(int channel, AMQBody methodBody, AMQBody headerBody) - { - _channel = channel; - _methodBody = methodBody; - _headerBody = headerBody; - - } - - public long getSize() - { - return OVERHEAD + _methodBody.getSize() + _headerBody.getSize() ; - } - - public void writePayload(DataOutput buffer) throws IOException - { - AMQFrame.writeFrames(buffer, _channel, _methodBody, _headerBody); - } - - @Override - public long writePayload(final ByteBufferSender sender) throws IOException - { - long size = (new AMQFrame(_channel, _methodBody)).writePayload(sender); - size += (new AMQFrame(_channel, _headerBody)).writePayload(sender); - return size; - } - - @Override - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append(getClass().getSimpleName()) - .append("methodBody=").append(_methodBody) - .append(", headerBody=").append(_headerBody) - .append(", channel=").append(_channel).append("]"); - return builder.toString(); - } - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/RecordDeliveryMethod.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/RecordDeliveryMethod.java deleted file mode 100644 index c13ff17f67..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/RecordDeliveryMethod.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.protocol.v0_8; - -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.MessageInstance; - -public interface RecordDeliveryMethod -{ - void recordMessageDelivery(final ConsumerImpl sub, final MessageInstance entry, final long deliveryTag); -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/UnacknowledgedMessageMap.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/UnacknowledgedMessageMap.java deleted file mode 100644 index 198b7fe21b..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/UnacknowledgedMessageMap.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.protocol.v0_8; - -import java.util.Collection; -import java.util.Map; -import java.util.Set; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.message.MessageInstance; - - -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, MessageInstance message); - - void visitComplete(); - } - - void visit(Visitor visitor); - - void add(long deliveryTag, MessageInstance message); - - MessageInstance remove(long deliveryTag); - - Collection cancelAllMessages(); - - int size(); - - void clear(); - - MessageInstance get(long deliveryTag); - - /** - * Get the set of delivery tags that are outstanding. - * - * @return a set of delivery tags - */ - Set getDeliveryTags(); - - Collection acknowledge(long deliveryTag, boolean multiple); - void collect(long key, boolean multiple, Map msgs); -} - - diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/UnacknowledgedMessageMapImpl.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/UnacknowledgedMessageMapImpl.java deleted file mode 100644 index 2d39daed1c..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/UnacknowledgedMessageMapImpl.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.protocol.v0_8; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.qpid.server.message.MessageInstance; - -public class UnacknowledgedMessageMapImpl implements UnacknowledgedMessageMap -{ - private final Object _lock = new Object(); - - private Map _map; - - private final int _prefetchLimit; - - public UnacknowledgedMessageMapImpl(int prefetchLimit) - { - _prefetchLimit = prefetchLimit; - _map = new LinkedHashMap<>(prefetchLimit); - } - - public void collect(long deliveryTag, boolean multiple, Map msgs) - { - if (multiple) - { - collect(deliveryTag, msgs); - } - else - { - final MessageInstance entry = get(deliveryTag); - if(entry != null) - { - msgs.put(deliveryTag, entry); - } - } - - } - - public void remove(Map msgs) - { - synchronized (_lock) - { - for (Long deliveryTag : msgs.keySet()) - { - remove(deliveryTag); - } - } - } - - public MessageInstance remove(long deliveryTag) - { - synchronized (_lock) - { - - MessageInstance message = _map.remove(deliveryTag); - return message; - } - } - - public void visit(Visitor visitor) - { - synchronized (_lock) - { - Set> currentEntries = _map.entrySet(); - for (Map.Entry entry : currentEntries) - { - visitor.callback(entry.getKey().longValue(), entry.getValue()); - } - visitor.visitComplete(); - } - } - - public void add(long deliveryTag, MessageInstance message) - { - synchronized (_lock) - { - _map.put(deliveryTag, message); - } - } - - public Collection cancelAllMessages() - { - synchronized (_lock) - { - Collection currentEntries = _map.values(); - _map = new LinkedHashMap<>(_prefetchLimit); - return currentEntries; - } - } - - public int size() - { - synchronized (_lock) - { - return _map.size(); - } - } - - public void clear() - { - synchronized (_lock) - { - _map.clear(); - } - } - - public MessageInstance get(long key) - { - synchronized (_lock) - { - return _map.get(key); - } - } - - public Set getDeliveryTags() - { - synchronized (_lock) - { - return _map.keySet(); - } - } - - public Collection acknowledge(long deliveryTag, boolean multiple) - { - Map ackedMessageMap = new LinkedHashMap(); - collect(deliveryTag, multiple, ackedMessageMap); - remove(ackedMessageMap); - List acknowledged = new ArrayList<>(); - for(MessageInstance instance : ackedMessageMap.values()) - { - if(instance.lockAcquisition()) - { - acknowledged.add(instance); - } - } - return acknowledged; - } - - private void collect(long key, Map msgs) - { - synchronized (_lock) - { - for (Map.Entry entry : _map.entrySet()) - { - msgs.put(entry.getKey(),entry.getValue()); - if (entry.getKey() == key) - { - break; - } - } - } - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/UnexpectedMethodException.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/UnexpectedMethodException.java deleted file mode 100644 index 432a725c86..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/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.protocol.v0_8; - - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQMethodBody; - -public class UnexpectedMethodException extends AMQException -{ - - private static final long serialVersionUID = -255921574946294892L; - - public UnexpectedMethodException(AMQMethodBody body) - { - super("Unexpected method received: " + body.getClass().getName()); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQChannelTest.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQChannelTest.java deleted file mode 100644 index a6725a6d58..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQChannelTest.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.server.protocol.v0_8; - -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.qpid.framing.AMQDataBlock; -import org.apache.qpid.framing.AMQFrame; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ChannelCloseBody; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.configuration.BrokerProperties; -import org.apache.qpid.server.exchange.ExchangeImpl; -import org.apache.qpid.server.message.MessageContentSource; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.test.utils.QpidTestCase; - -public class AMQChannelTest extends QpidTestCase -{ - private VirtualHostImpl _virtualHost; - private AMQProtocolEngine _protocolSession; - private Map _replies; - private Broker _broker; - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _virtualHost = BrokerTestHelper.createVirtualHost(getTestName()); - _broker = BrokerTestHelper.createBrokerMock(); - AmqpPort port = mock(AmqpPort.class); - when(port.getContextValue(eq(Integer.class), eq(AmqpPort.PORT_MAX_MESSAGE_SIZE))).thenReturn(AmqpPort.DEFAULT_MAX_MESSAGE_SIZE); - - _protocolSession = new InternalTestProtocolSession(_virtualHost, _broker, port) - { - @Override - public void writeReturn(MessagePublishInfo messagePublishInfo, - ContentHeaderBody header, - MessageContentSource msgContent, - int channelId, - int replyCode, - AMQShortString replyText) - { - _replies.put(replyCode, replyText.asString()); - } - }; - _replies = new HashMap(); - } - - @Override - public void tearDown() throws Exception - { - try - { - _virtualHost.close(); - } - finally - { - BrokerTestHelper.tearDown(); - super.tearDown(); - } - } - - public void testCompareTo() throws Exception - { - AMQChannel channel1 = new AMQChannel(_protocolSession, 1, _virtualHost.getMessageStore()); - - AmqpPort port = mock(AmqpPort.class); - when(port.getContextValue(eq(Integer.class), eq(AmqpPort.PORT_MAX_MESSAGE_SIZE))).thenReturn(AmqpPort.DEFAULT_MAX_MESSAGE_SIZE); - // create a channel with the same channelId but on a different session - AMQChannel channel2 = new AMQChannel(new InternalTestProtocolSession(_virtualHost, _broker, port), 1, _virtualHost.getMessageStore()); - assertFalse("Unexpected compare result", channel1.compareTo(channel2) == 0); - assertEquals("Unexpected compare result", 0, channel1.compareTo(channel1)); - } - - public void testPublishContentHeaderWhenMessageAuthorizationFails() throws Exception - { - setTestSystemProperty(BrokerProperties.PROPERTY_MSG_AUTH, "true"); - AMQChannel channel = new AMQChannel(_protocolSession, 1, _virtualHost.getMessageStore()); - channel.setLocalTransactional(); - - MessagePublishInfo info = new MessagePublishInfo(new AMQShortString("test"), false, false, null); - ExchangeImpl e = mock(ExchangeImpl.class); - ContentHeaderBody contentHeaderBody= mock(ContentHeaderBody.class); - BasicContentHeaderProperties properties = mock(BasicContentHeaderProperties.class); - - when(contentHeaderBody.getProperties()).thenReturn(properties); - when(properties.getUserId()).thenReturn(new AMQShortString(_protocolSession.getAuthorizedPrincipal().getName() + "_incorrect")); - - channel.setPublishFrame(info, e); - channel.publishContentHeader(contentHeaderBody); - channel.commit(null, false); - - assertEquals("Unexpected number of replies", 1, _replies.size()); - assertEquals("Message authorization passed", "Access Refused", _replies.get(403)); - } - - public void testPublishContentHeaderWhenMessageAuthorizationPasses() throws Exception - { - setTestSystemProperty(BrokerProperties.PROPERTY_MSG_AUTH, "true"); - AMQChannel channel = new AMQChannel(_protocolSession, 1, _virtualHost.getMessageStore()); - channel.setLocalTransactional(); - - MessagePublishInfo info = new MessagePublishInfo(new AMQShortString("test"), false, false, null); - ExchangeImpl e = mock(ExchangeImpl.class); - ContentHeaderBody contentHeaderBody= mock(ContentHeaderBody.class); - BasicContentHeaderProperties properties = mock(BasicContentHeaderProperties.class); - - when(contentHeaderBody.getProperties()).thenReturn(properties); - when(properties.getUserId()).thenReturn(new AMQShortString(_protocolSession.getAuthorizedPrincipal().getName())); - - channel.setPublishFrame(info, e); - channel.publishContentHeader(contentHeaderBody); - channel.commit(null, false); - - assertEquals("Unexpected number of replies", 0, _replies.size()); - } - - public void testOverlargeMessage() throws Exception - { - - AmqpPort port = mock(AmqpPort.class); - when(port.getContextValue(eq(Integer.class), eq(AmqpPort.PORT_MAX_MESSAGE_SIZE))).thenReturn(1024); - final List frames = new ArrayList<>(); - _protocolSession = new InternalTestProtocolSession(_virtualHost, _broker, port) - { - @Override - public synchronized void writeFrame(final AMQDataBlock frame) - { - frames.add(frame); - } - }; - - AMQChannel channel = new AMQChannel(_protocolSession, 1, _virtualHost.getMessageStore()); - - channel.receiveBasicPublish(AMQShortString.EMPTY_STRING, AMQShortString.EMPTY_STRING, false, false); - - final BasicContentHeaderProperties properties = new BasicContentHeaderProperties(); - channel.receiveMessageHeader(properties, 2048l); - - frames.toString(); - - assertEquals(1, frames.size()); - assertEquals(ChannelCloseBody.class, ((AMQFrame) frames.get(0)).getBodyFrame().getClass()); - assertEquals(AMQConstant.MESSAGE_TOO_LARGE.getCode(), ((ChannelCloseBody)((AMQFrame)frames.get(0)).getBodyFrame()).getReplyCode()); - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQProtocolEngineTest.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQProtocolEngineTest.java deleted file mode 100644 index cc5da731b8..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQProtocolEngineTest.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.protocol.v0_8; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.nio.ByteBuffer; -import java.util.HashMap; -import java.util.Map; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQFrameDecodingException; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.properties.ConnectionStartProperties; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.server.util.ServerScopedRuntimeException; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.transport.ByteBufferSender; -import org.apache.qpid.transport.SenderException; -import org.apache.qpid.transport.network.NetworkConnection; - -public class AMQProtocolEngineTest extends QpidTestCase -{ - private Broker _broker; - private AmqpPort _port; - private NetworkConnection _network; - private Transport _transport; - - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _broker = BrokerTestHelper.createBrokerMock(); - when(_broker.getConnection_closeWhenNoRoute()).thenReturn(true); - - _port = mock(AmqpPort.class); - when(_port.getContextValue(eq(Integer.class), eq(AmqpPort.PORT_MAX_MESSAGE_SIZE))).thenReturn(AmqpPort.DEFAULT_MAX_MESSAGE_SIZE); - - _network = mock(NetworkConnection.class); - _transport = Transport.TCP; - } - - public void tearDown() throws Exception - { - try - { - super.tearDown(); - } - finally - { - BrokerTestHelper.tearDown(); - } - } - - public void testSetClientPropertiesForNoRouteProvidedAsString() - { - AMQProtocolEngine engine = new AMQProtocolEngine(_broker, _network, 0, _port, _transport); - assertTrue("Unexpected closeWhenNoRoute before client properties set", engine.isCloseWhenNoRoute()); - - Map clientProperties = new HashMap(); - clientProperties.put(ConnectionStartProperties.QPID_CLOSE_WHEN_NO_ROUTE, Boolean.FALSE.toString()); - engine.setClientProperties(FieldTable.convertToFieldTable(clientProperties)); - - assertFalse("Unexpected closeWhenNoRoute after client properties set", engine.isCloseWhenNoRoute()); - } - - public void testSetClientPropertiesForNoRouteProvidedAsBoolean() - { - AMQProtocolEngine engine = new AMQProtocolEngine(_broker, _network, 0, _port, _transport); - assertTrue("Unexpected closeWhenNoRoute before client properties set", engine.isCloseWhenNoRoute()); - - Map clientProperties = new HashMap(); - clientProperties.put(ConnectionStartProperties.QPID_CLOSE_WHEN_NO_ROUTE, Boolean.FALSE); - engine.setClientProperties(FieldTable.convertToFieldTable(clientProperties)); - - assertFalse("Unexpected closeWhenNoRoute after client properties set", engine.isCloseWhenNoRoute()); - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AckTest.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AckTest.java deleted file mode 100644 index 406566cd4c..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AckTest.java +++ /dev/null @@ -1,353 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.v0_8; - - -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.Set; - -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.MessagePublishInfo; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.store.MessageEnqueueRecord; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.store.TestMemoryMessageStore; -import org.apache.qpid.server.txn.AutoCommitTransaction; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.test.utils.QpidTestCase; - -/** - * Tests that acknowledgements are handled correctly. - */ -public class AckTest extends QpidTestCase -{ - private ConsumerTarget_0_8 _subscriptionTarget; - private ConsumerImpl _consumer; - - private AMQProtocolEngine _protocolEngine; - - private TestMemoryMessageStore _messageStore; - - private AMQChannel _channel; - - private AMQQueue _queue; - - private static final AMQShortString DEFAULT_CONSUMER_TAG = new AMQShortString("conTag"); - private VirtualHostImpl _virtualHost; - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _channel = BrokerTestHelper_0_8.createChannel(5); - _protocolEngine = _channel.getConnection(); - _virtualHost = _protocolEngine.getVirtualHost(); - _queue = BrokerTestHelper.createQueue(getTestName(), _virtualHost); - _messageStore = (TestMemoryMessageStore)_virtualHost.getMessageStore(); - } - - @Override - protected void tearDown() throws Exception - { - BrokerTestHelper.tearDown(); - super.tearDown(); - } - - private void publishMessages(int count) throws AMQException - { - publishMessages(count, false); - } - - private void publishMessages(int count, boolean persistent) throws AMQException - { - for (int i = 1; i <= count; i++) - { - MessagePublishInfo publishBody = new MessagePublishInfo(new AMQShortString("someExchange"), false, false, - new AMQShortString("rk")); - BasicContentHeaderProperties b = new BasicContentHeaderProperties(); - ContentHeaderBody cb = new ContentHeaderBody(b); - - if (persistent) - { - //This is DeliveryMode.PERSISTENT - b.setDeliveryMode((byte) 2); - } - - // The test is easier to construct if we have direct access to the subscription - ArrayList qs = new ArrayList(); - qs.add(_queue); - - final MessageMetaData mmd = new MessageMetaData(publishBody,cb, System.currentTimeMillis()); - - final StoredMessage result =_messageStore.addMessage(mmd).allContentAdded(); - - final StoredMessage storedMessage = result; - final AMQMessage message = new AMQMessage(storedMessage); - ServerTransaction txn = new AutoCommitTransaction(_messageStore); - txn.enqueue(_queue, message, - new ServerTransaction.EnqueueAction() - { - public void postCommit(MessageEnqueueRecord... records) - { - _queue.enqueue(message,null, null); - } - - public void onRollback() - { - } - }); - - } - try - { - Thread.sleep(2000L); - } - catch (InterruptedException e) - { - Thread.currentThread().interrupt(); - } - - } - - /** - * Tests that the acknowledgements are correctly associated with a channel and - * order is preserved when acks are enabled - */ - public void testAckChannelAssociationTest() throws Exception - { - _subscriptionTarget = ConsumerTarget_0_8.createAckTarget(_channel, - DEFAULT_CONSUMER_TAG, - null, - new LimitlessCreditManager()); - _consumer = _queue.addConsumer(_subscriptionTarget, null, AMQMessage.class, DEFAULT_CONSUMER_TAG.toString(), - EnumSet.of(ConsumerImpl.Option.SEES_REQUEUES, - ConsumerImpl.Option.ACQUIRES)); - final int msgCount = 10; - publishMessages(msgCount, true); - UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap(); - assertEquals("Unexpected size for unacknowledged message map",msgCount,map.size()); - - Set deliveryTagSet = map.getDeliveryTags(); - int i = 1; - for (long deliveryTag : deliveryTagSet) - { - assertTrue(deliveryTag == i); - i++; - MessageInstance unackedMsg = map.get(deliveryTag); - assertTrue(unackedMsg.getOwningResource() == _queue); - } - - } - - /** - * Tests that in no-ack mode no messages are retained - */ - public void testNoAckMode() throws Exception - { - // false arg means no acks expected - _subscriptionTarget = ConsumerTarget_0_8.createNoAckTarget(_channel, - DEFAULT_CONSUMER_TAG, - null, - new LimitlessCreditManager()); - _consumer = _queue.addConsumer(_subscriptionTarget, - null, - AMQMessage.class, - DEFAULT_CONSUMER_TAG.toString(), - EnumSet.of(ConsumerImpl.Option.SEES_REQUEUES, - ConsumerImpl.Option.ACQUIRES)); - 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 Exception - { - // false arg means no acks expected - - _subscriptionTarget = ConsumerTarget_0_8.createNoAckTarget(_channel, - DEFAULT_CONSUMER_TAG, - null, - new LimitlessCreditManager()); - _consumer = _queue.addConsumer(_subscriptionTarget, null, AMQMessage.class, DEFAULT_CONSUMER_TAG.toString(), - EnumSet.of(ConsumerImpl.Option.SEES_REQUEUES, ConsumerImpl.Option.ACQUIRES)); - 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 Exception - { - - _subscriptionTarget = ConsumerTarget_0_8.createAckTarget(_channel, - DEFAULT_CONSUMER_TAG, - null, - new LimitlessCreditManager()); - _consumer = _queue.addConsumer(_subscriptionTarget, null, AMQMessage.class, DEFAULT_CONSUMER_TAG.toString(), - EnumSet.of(ConsumerImpl.Option.SEES_REQUEUES, - ConsumerImpl.Option.ACQUIRES)); - - final int msgCount = 10; - publishMessages(msgCount); - - _channel.acknowledgeMessage(5, false); - UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap(); - assertEquals("Map not expected size",msgCount - 1,map.size()); - - Set deliveryTagSet = map.getDeliveryTags(); - int i = 1; - for (long deliveryTag : deliveryTagSet) - { - assertTrue(deliveryTag == i); - MessageInstance unackedMsg = map.get(deliveryTag); - assertTrue(unackedMsg.getOwningResource() == _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 Exception - { - - _subscriptionTarget = ConsumerTarget_0_8.createAckTarget(_channel, - DEFAULT_CONSUMER_TAG, - null, - new LimitlessCreditManager()); - _consumer = _queue.addConsumer(_subscriptionTarget, null, AMQMessage.class, DEFAULT_CONSUMER_TAG.toString(), - EnumSet.of(ConsumerImpl.Option.SEES_REQUEUES, - ConsumerImpl.Option.ACQUIRES)); - - final int msgCount = 10; - publishMessages(msgCount); - - - - _channel.acknowledgeMessage(5, true); - UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap(); - assertTrue(map.size() == 5); - - Set deliveryTagSet = map.getDeliveryTags(); - int i = 1; - for (long deliveryTag : deliveryTagSet) - { - assertTrue(deliveryTag == i + 5); - MessageInstance unackedMsg = map.get(deliveryTag); - assertTrue(unackedMsg.getOwningResource() == _queue); - ++i; - } - } - - /** - * Tests that a multiple acknowledgement is handled correctly. When ack'ing all pending msgs. - */ - public void testMultiAckAllReceivedTest() throws Exception - { - - _subscriptionTarget = ConsumerTarget_0_8.createAckTarget(_channel, - DEFAULT_CONSUMER_TAG, - null, - new LimitlessCreditManager()); - _consumer = _queue.addConsumer(_subscriptionTarget, null, AMQMessage.class, DEFAULT_CONSUMER_TAG.toString(), - EnumSet.of(ConsumerImpl.Option.SEES_REQUEUES, - ConsumerImpl.Option.ACQUIRES)); - - final int msgCount = 10; - publishMessages(msgCount); - - _channel.acknowledgeMessage(0, true); - UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap(); - assertTrue(map.size() == 0); - - Set deliveryTagSet = map.getDeliveryTags(); - int i = 1; - for (long deliveryTag : deliveryTagSet) - { - assertTrue(deliveryTag == i + 5); - MessageInstance unackedMsg = map.get(deliveryTag); - assertTrue(unackedMsg.getOwningResource() == _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, _protocolEngine); - - - _subscriptionTarget = ConsumerTarget_0_8.createAckTarget(_channel, DEFAULT_CONSUMER_TAG, null, creditManager); - _consumer = _queue.addConsumer(_subscriptionTarget, null, AMQMessage.class, DEFAULT_CONSUMER_TAG.toString(), - EnumSet.of(ConsumerImpl.Option.SEES_REQUEUES, - ConsumerImpl.Option.ACQUIRES)); - - final int msgCount = 1; - publishMessages(msgCount); - - _consumer.externalStateChange(); - - _channel.acknowledgeMessage(1, false); - - // Check credit available - assertTrue("No credit available", creditManager.hasCredit()); - - } - - public static junit.framework.Test suite() - { - return new junit.framework.TestSuite(AckTest.class); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AcknowledgeTest.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AcknowledgeTest.java deleted file mode 100644 index 7dd4734e6b..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AcknowledgeTest.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.protocol.v0_8; - -import java.util.Collections; -import java.util.List; - -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.message.MessageSource; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.store.MessageCounter; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.test.utils.QpidTestCase; - -public class AcknowledgeTest extends QpidTestCase -{ - private AMQChannel _channel; - private AMQQueue _queue; - private MessageStore _messageStore; - private String _queueName; - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _channel = BrokerTestHelper_0_8.createChannel(); - VirtualHostImpl virtualHost = _channel.getVirtualHost(); - _queueName = getTestName(); - _queue = BrokerTestHelper.createQueue(_queueName, virtualHost); - _messageStore = virtualHost.getMessageStore(); - } - - @Override - public void tearDown() throws Exception - { - try - { - if (_channel != null) - { - _channel.getVirtualHost().close(); - } - } - finally - { - BrokerTestHelper.tearDown(); - super.tearDown(); - } - } - - private AMQChannel getChannel() - { - return _channel; - } - - private InternalTestProtocolSession getSession() - { - return (InternalTestProtocolSession)_channel.getConnection(); - } - - private AMQQueue getQueue() - { - return _queue; - } - - public void testTransactionalSingleAck() throws Exception - { - getChannel().setLocalTransactional(); - runMessageAck(1, 1, 1, false, 0); - } - - public void testTransactionalMultiAck() throws Exception - { - getChannel().setLocalTransactional(); - runMessageAck(10, 1, 5, true, 5); - } - - public void testTransactionalAckAll() throws Exception - { - getChannel().setLocalTransactional(); - runMessageAck(10, 1, 0, true, 0); - } - - public void testNonTransactionalSingleAck() throws Exception - { - runMessageAck(1, 1, 1, false, 0); - } - - public void testNonTransactionalMultiAck() throws Exception - { - runMessageAck(10, 1, 5, true, 5); - } - - public void testNonTransactionalAckAll() throws Exception - { - runMessageAck(10, 1, 0, true, 0); - } - - protected void runMessageAck(int sendMessageCount, long firstDeliveryTag, long acknowledgeDeliveryTag, boolean acknowledgeMultiple, int remainingUnackedMessages) throws Exception - { - //Check store is empty - checkStoreContents(0); - - //Send required messages to the queue - BrokerTestHelper_0_8.publishMessages(getChannel(), - sendMessageCount, - _queueName, - ExchangeDefaults.DEFAULT_EXCHANGE_NAME); - - if (getChannel().isTransactional()) - { - getChannel().commit(null, false); - } - - //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 = _channel.consumeFromSource(null, - Collections.singleton(_queue), - true, null, true, false); - - getQueue().deliverAsync(); - - //Wait for the messages to be delivered - getSession().awaitDelivery(sendMessageCount); - - //Check that they are all waiting to be acknowledged - assertEquals("Channel should have unacked msgs", sendMessageCount, getChannel().getUnacknowledgedMessageMap().size()); - - List 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, acknowledgeMultiple); - - if (getChannel().isTransactional()) - { - getChannel().commit(null, false); - } - - // Check Remaining Acknowledgements - assertEquals("Channel unacked msgs count incorrect", remainingUnackedMessages, getChannel().getUnacknowledgedMessageMap().size()); - - //Check store contents are also correct. - checkStoreContents(remainingUnackedMessages); - } - - private void checkStoreContents(int messageCount) - { - MessageCounter counter = new MessageCounter(); - _messageStore.newMessageStoreReader().visitMessages(counter); - assertEquals("Message header count incorrect in the MetaDataMap", messageCount, counter.getCount()); - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/BrokerTestHelper_0_8.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/BrokerTestHelper_0_8.java deleted file mode 100644 index a0a3d60458..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/BrokerTestHelper_0_8.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.protocol.v0_8; - -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -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.MessagePublishInfo; -import org.apache.qpid.server.message.MessageDestination; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; - -public class BrokerTestHelper_0_8 extends BrokerTestHelper -{ - - public static AMQChannel createChannel(int channelId, AMQProtocolEngine session) throws AMQException - { - AMQChannel channel = new AMQChannel(session, channelId, session.getVirtualHost().getMessageStore()); - session.addChannel(channel); - return channel; - } - - public static AMQChannel createChannel(int channelId) throws Exception - { - InternalTestProtocolSession session = createProtocolSession(); - return createChannel(channelId, session); - } - - public static AMQChannel createChannel() throws Exception - { - return createChannel(1); - } - - public static InternalTestProtocolSession createProtocolSession() throws Exception - { - return createProtocolSession("test"); - } - - public static InternalTestProtocolSession createProtocolSession(String hostName) throws Exception - { - VirtualHostImpl virtualHost = createVirtualHost(hostName); - - AmqpPort port = mock(AmqpPort.class); - when(port.getContextValue(eq(Integer.class), eq(AmqpPort.PORT_MAX_MESSAGE_SIZE))).thenReturn(AmqpPort.DEFAULT_MAX_MESSAGE_SIZE); - return new InternalTestProtocolSession(virtualHost, createBrokerMock(), port); - } - - public static void publishMessages(AMQChannel channel, int numberOfMessages, String queueName, String exchangeName) - throws AMQException - { - AMQShortString routingKey = new AMQShortString(queueName); - AMQShortString exchangeNameAsShortString = new AMQShortString(exchangeName); - MessagePublishInfo info = new MessagePublishInfo(exchangeNameAsShortString, false, false, routingKey); - - MessageDestination destination; - if(exchangeName == null || "".equals(exchangeName)) - { - destination = channel.getVirtualHost().getDefaultDestination(); - } - else - { - destination = channel.getVirtualHost().getExchange(exchangeName); - } - for (int count = 0; count < numberOfMessages; count++) - { - channel.setPublishFrame(info, destination); - - - // Set Minimum properties - BasicContentHeaderProperties properties = new BasicContentHeaderProperties(); - - - properties.setExpiration(0L); - properties.setTimestamp(System.currentTimeMillis()); - - // Make Message Persistent - properties.setDeliveryMode((byte) 2); - - ContentHeaderBody headerBody = new ContentHeaderBody(properties, 0); - - channel.publishContentHeader(headerBody); - } - channel.sync(); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/ExtractResendAndRequeueTest.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/ExtractResendAndRequeueTest.java deleted file mode 100644 index 6d3e648369..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/ExtractResendAndRequeueTest.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.protocol.v0_8; - -import junit.framework.TestCase; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.QueueEntry; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.Map; - -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * 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 complete 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 occurring 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 -{ - - private UnacknowledgedMessageMapImpl _unacknowledgedMessageMap; - private static final int INITIAL_MSG_COUNT = 10; - private AMQQueue _queue; - private LinkedList _referenceList = new LinkedList(); - private ConsumerImpl _consumer; - private boolean _queueDeleted; - - @Override - public void setUp() throws AMQException - { - _queueDeleted = false; - _unacknowledgedMessageMap = new UnacknowledgedMessageMapImpl(100); - _queue = mock(AMQQueue.class); - when(_queue.getName()).thenReturn(getName()); - when(_queue.isDeleted()).thenReturn(_queueDeleted); - _consumer = mock(ConsumerImpl.class); - when(_consumer.getConsumerNumber()).thenReturn(ConsumerImpl.CONSUMER_NUMBER_GENERATOR.getAndIncrement()); - - - long id = 0; - - // Add initial messages to QueueEntryList - for (int count = 0; count < INITIAL_MSG_COUNT; count++) - { - ServerMessage msg = mock(ServerMessage.class); - when(msg.getMessageNumber()).thenReturn(id); - final QueueEntry entry = mock(QueueEntry.class); - when(entry.getMessage()).thenReturn(msg); - when(entry.getQueue()).thenReturn(_queue); - when(entry.isQueueDeleted()).thenReturn(_queueDeleted); - doAnswer(new Answer() - { - @Override - public Object answer(final InvocationOnMock invocation) throws Throwable - { - when(entry.isDeleted()).thenReturn(true); - return null; - } - }).when(entry).delete(); - - _unacknowledgedMessageMap.add(id, entry); - _referenceList.add(entry); - //Increment ID; - id++; - } - - assertEquals("Map does not contain correct setup data", INITIAL_MSG_COUNT, _unacknowledgedMessageMap.size()); - } - - /** - * Helper method to create a new subscription and acquire the given messages. - * - * @param messageList The messages to acquire - * - * @return Subscription that performed the acquire - */ - private void acquireMessages(LinkedList messageList) - { - - // Acquire messages in subscription - for(MessageInstance entry : messageList) - { - when(entry.getDeliveredConsumer()).thenReturn(_consumer); - } - } - - /** - * This is the normal consumer rollback method. - * - * An active consumer that has acquired messages expects those messages 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. - acquireMessages(_referenceList); - - final Map msgToRequeue = new LinkedHashMap(); - final Map msgToResend = new LinkedHashMap(); - - // requeueIfUnableToResend doesn't matter here. - _unacknowledgedMessageMap.visit(new ExtractResendAndRequeue(_unacknowledgedMessageMap, msgToRequeue, - msgToResend)); - - 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 acquired messages expects closes the messages that it has acquired should be removed from - * the unacknowledgedMap 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 - { - acquireMessages(_referenceList); - - // Close subscription - when(_consumer.isClosed()).thenReturn(true); - - final Map msgToRequeue = new LinkedHashMap(); - final Map msgToResend = new LinkedHashMap(); - - // requeueIfUnableToResend doesn't matter here. - _unacknowledgedMessageMap.visit(new ExtractResendAndRequeue(_unacknowledgedMessageMap, msgToRequeue, - msgToResend)); - - 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()); - } - - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/InternalTestProtocolSession.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/InternalTestProtocolSession.java deleted file mode 100644 index 7e68bee661..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/InternalTestProtocolSession.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.server.protocol.v0_8; - -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.security.Principal; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; - -import javax.security.auth.Subject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.MessageContentSource; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; -import org.apache.qpid.server.security.auth.UsernamePrincipal; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.ByteBufferSender; -import org.apache.qpid.transport.network.NetworkConnection; - -public class InternalTestProtocolSession extends AMQProtocolEngine implements ProtocolOutputConverter -{ - private static final Logger _logger = LoggerFactory.getLogger(InternalTestProtocolSession.class); - // ChannelID(LIST) -> LinkedList - private final Map>> _channelDelivers; - private AtomicInteger _deliveryCount = new AtomicInteger(0); - private static final AtomicLong ID_GENERATOR = new AtomicLong(0); - - public InternalTestProtocolSession(VirtualHostImpl virtualHost, Broker broker, final AmqpPort port) throws AMQException - { - super(broker, new TestNetworkConnection(), ID_GENERATOR.getAndIncrement(), port, null); - - _channelDelivers = new HashMap>>(); - - setTestAuthorizedSubject(); - setVirtualHost(virtualHost); - } - - private void setTestAuthorizedSubject() - { - Principal principal = new AuthenticatedPrincipal(new UsernamePrincipal("InternalTestProtocolSession")); - Subject authorizedSubject = new Subject( - true, - Collections.singleton(principal), - Collections.emptySet(), - Collections.emptySet()); - - setAuthorizedSubject(authorizedSubject); - } - - 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) - { - //To change body of implemented methods use File | Settings | File Templates. - } - - public byte getProtocolMinorVersion() - { - return (byte) 0; - } - - // *** - - public List getDelivers(int channelId, AMQShortString consumerTag, int count) - { - synchronized (_channelDelivers) - { - List all =_channelDelivers.get(channelId).get(AMQShortString.toString(consumerTag)); - - if (all == null) - { - return new ArrayList(0); - } - - List msgs = all.subList(0, count); - - List response = new ArrayList(msgs); - - //Remove the msgs from the receivedList. - msgs.clear(); - - return response; - } - } - - public ClientDeliveryMethod createDeliveryMethod(int channelId) - { - return new InternalWriteDeliverMethod(channelId); - } - - public void confirmConsumerAutoClose(int channelId, AMQShortString consumerTag) - { - } - - public long writeDeliver(final ServerMessage msg, - final InstanceProperties props, int channelId, - long deliveryTag, - AMQShortString consumerTag) - { - _deliveryCount.incrementAndGet(); - long size = msg.getSize(); - synchronized (_channelDelivers) - { - Map> consumers = _channelDelivers.get(channelId); - - if (consumers == null) - { - consumers = new HashMap>(); - _channelDelivers.put(channelId, consumers); - } - - LinkedList consumerDelivers = consumers.get(AMQShortString.toString(consumerTag)); - - if (consumerDelivers == null) - { - consumerDelivers = new LinkedList(); - consumers.put(consumerTag.toString(), consumerDelivers); - } - - consumerDelivers.add(new DeliveryPair(deliveryTag, msg)); - } - return size; - } - - public long writeGetOk(final ServerMessage msg, - final InstanceProperties props, - int channelId, - long deliveryTag, - int queueSize) - { - return msg.getSize(); - } - - public void awaitDelivery(int msgs) - { - while (msgs > _deliveryCount.get()) - { - try - { - Thread.sleep(100); - } - catch (InterruptedException e) - { - _logger.error("Thread interrupted", e); - } - } - } - - public class DeliveryPair - { - private long _deliveryTag; - private ServerMessage _message; - - public DeliveryPair(long deliveryTag, ServerMessage message) - { - _deliveryTag = deliveryTag; - _message = message; - } - - public ServerMessage getMessage() - { - return _message; - } - - public long getDeliveryTag() - { - return _deliveryTag; - } - } - - public void closeNetworkConnection() - { - // 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. - } - - private class InternalWriteDeliverMethod implements ClientDeliveryMethod - { - private int _channelId; - - public InternalWriteDeliverMethod(int channelId) - { - _channelId = channelId; - } - - - @Override - public long deliverToClient(ConsumerImpl sub, ServerMessage message, - InstanceProperties props, long deliveryTag) - { - _deliveryCount.incrementAndGet(); - long size = message.getSize(); - synchronized (_channelDelivers) - { - Map> consumers = _channelDelivers.get(_channelId); - - if (consumers == null) - { - consumers = new HashMap>(); - _channelDelivers.put(_channelId, consumers); - } - - LinkedList consumerDelivers = consumers.get(sub.getName()); - - if (consumerDelivers == null) - { - consumerDelivers = new LinkedList(); - consumers.put(sub.getName(), consumerDelivers); - } - - consumerDelivers.add(new DeliveryPair(deliveryTag, message)); - } - return size; - } - } - - void assertState(final ConnectionState requiredState) - { - // no-op - } - - - private static final AtomicInteger portNumber = new AtomicInteger(0); - - private static class TestNetworkConnection implements NetworkConnection - { - private String _remoteHost = "127.0.0.1"; - private String _localHost = "127.0.0.1"; - private int _port = portNumber.incrementAndGet(); - private final ByteBufferSender _sender; - - public TestNetworkConnection() - { - _sender = new ByteBufferSender() - { - public void send(ByteBuffer msg) - { - } - - public void flush() - { - } - - public void close() - { - } - }; - } - - @Override - public SocketAddress getLocalAddress() - { - return new InetSocketAddress(_localHost, _port); - } - - @Override - public SocketAddress getRemoteAddress() - { - return new InetSocketAddress(_remoteHost, _port); - } - - @Override - public void setMaxReadIdle(int idleTime) - { - } - - @Override - public Principal getPeerPrincipal() - { - return null; - } - - @Override - public int getMaxReadIdle() - { - return 0; - } - - @Override - public int getMaxWriteIdle() - { - return 0; - } - - @Override - public void setMaxWriteIdle(int idleTime) - { - } - - @Override - public void close() - { - } - - @Override - public ByteBufferSender getSender() - { - return _sender; - } - - @Override - public void start() - { - } - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/LimitlessCreditManager.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/LimitlessCreditManager.java deleted file mode 100644 index c4c89ac24a..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/LimitlessCreditManager.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.protocol.v0_8; - - -import org.apache.qpid.server.flow.AbstractFlowCreditManager; -import org.apache.qpid.server.flow.FlowCreditManager; - -public class LimitlessCreditManager extends AbstractFlowCreditManager implements FlowCreditManager -{ - - public void restoreCredit(long messageCredit, long bytesCredit) - { - } - - public void removeAllCredit() - { - } - - public boolean hasCredit() - { - return true; - } - - public boolean useCreditForMessage(long msgSize) - { - return true; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MaxChannelsTest.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MaxChannelsTest.java deleted file mode 100644 index 459fc94484..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MaxChannelsTest.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.v0_8; - -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.test.utils.QpidTestCase; - -public class MaxChannelsTest extends QpidTestCase -{ - private AMQProtocolEngine _session; - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _session = BrokerTestHelper_0_8.createProtocolSession(); - } - - public void testChannels() throws Exception - { - // 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.", maxChannels, _session.getMaximumNumberOfChannels()); - - for (long currentChannel = 1L; currentChannel <= maxChannels; currentChannel++) - { - _session.receiveChannelOpen( (int) currentChannel); - } - assertFalse("Connection should not be closed after opening " + maxChannels + " channels",_session.isClosed()); - assertEquals("Maximum number of channels not set.", maxChannels, _session.getChannels().size()); - _session.receiveChannelOpen((int) maxChannels+1); - assertTrue("Connection should be closed after opening " + (maxChannels + 1) + " channels",_session.isClosed()); - } - - @Override - public void tearDown() throws Exception - { - try - { - _session.getVirtualHost().close(); - } - finally - { - BrokerTestHelper.tearDown(); - super.tearDown(); - } - } - -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MockAMQMessage.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MockAMQMessage.java deleted file mode 100644 index 1cc3607298..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MockAMQMessage.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.protocol.v0_8; - -public class MockAMQMessage extends AMQMessage -{ - public MockAMQMessage(long messageId) - { - super(new MockStoredMessage(messageId)); - } - - public MockAMQMessage(long messageId, String headerName, Object headerValue) - { - super(new MockStoredMessage(messageId, headerName, headerValue)); - } - - @Override - public long getSize() - { - return 0l; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MockStoredMessage.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MockStoredMessage.java deleted file mode 100755 index c6aea39aa6..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MockStoredMessage.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.protocol.v0_8; - -import java.nio.ByteBuffer; - -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.server.store.MessageHandle; -import org.apache.qpid.server.store.StoredMessage; - -public class MockStoredMessage implements StoredMessage, MessageHandle -{ - private long _messageId; - private MessageMetaData _metaData; - private final ByteBuffer _content; - - public MockStoredMessage(long messageId) - { - this(messageId, (String)null, null); - } - - public MockStoredMessage(long messageId, String headerName, Object headerValue) - { - this(messageId, new MessagePublishInfo(null, false, false, null), new ContentHeaderBody(new BasicContentHeaderProperties()), headerName, headerValue); - } - - public MockStoredMessage(long messageId, MessagePublishInfo info, ContentHeaderBody chb) - { - this(messageId, info, chb, null, null); - } - - public MockStoredMessage(long messageId, MessagePublishInfo info, ContentHeaderBody chb, String headerName, Object headerValue) - { - _messageId = messageId; - if (headerName != null) - { - FieldTable headers = new FieldTable(); - headers.setString(headerName, headerValue == null? null :String.valueOf(headerValue)); - ( chb.getProperties()).setHeaders(headers); - } - _metaData = new MessageMetaData(info, chb); - _content = ByteBuffer.allocate(_metaData.getContentSize()); - } - - public MessageMetaData getMetaData() - { - return _metaData; - } - - public long getMessageNumber() - { - return _messageId; - } - - public void addContent(ByteBuffer src) - { - src = src.duplicate(); - _content.put(src); - } - - @Override - public StoredMessage allContentAdded() - { - _content.flip(); - return this; - } - - 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 ByteBuffer getContent(int offsetInMessage, int size) - { - ByteBuffer buf = ByteBuffer.allocate(size); - getContent(offsetInMessage, buf); - buf.position(0); - return buf; - } - - public void remove() - { - } - - @Override - public boolean isInMemory() - { - return true; - } - - @Override - public boolean flowToDisk() - { - return false; - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/QueueBrowserUsesNoAckTest.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/QueueBrowserUsesNoAckTest.java deleted file mode 100644 index 264350ff8d..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/QueueBrowserUsesNoAckTest.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.v0_8; - -import java.util.Collections; -import java.util.List; - -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.message.MessageSource; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.store.MessageCounter; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.test.utils.QpidTestCase; - -public class QueueBrowserUsesNoAckTest extends QpidTestCase -{ - private AMQChannel _channel; - private AMQQueue _queue; - private MessageStore _messageStore; - private String _queueName; - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _channel = BrokerTestHelper_0_8.createChannel(); - VirtualHostImpl virtualHost = _channel.getVirtualHost(); - _queueName = getTestName(); - _queue = BrokerTestHelper.createQueue(_queueName, virtualHost); - _messageStore = virtualHost.getMessageStore(); - } - - @Override - public void tearDown() throws Exception - { - try - { - if (_channel != null) - { - _channel.getVirtualHost().close(); - } - } - finally - { - BrokerTestHelper.tearDown(); - super.tearDown(); - } - } - - private AMQChannel getChannel() - { - return _channel; - } - - private InternalTestProtocolSession getSession() - { - return (InternalTestProtocolSession)_channel.getConnection(); - } - - private AMQQueue getQueue() - { - return _queue; - } - - public void testQueueBrowserUsesNoAck() throws Exception - { - int sendMessageCount = 2; - int prefetch = 1; - - //Check store is empty - checkStoreContents(0); - - //Send required messages to the queue - BrokerTestHelper_0_8.publishMessages(getChannel(), - sendMessageCount, - _queueName, - ExchangeDefaults.DEFAULT_EXCHANGE_NAME); - - //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 messages = - getSession().getDelivers(getChannel().getChannelId(), browser, - prefetch); - - //Ensure we received 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).isSuspended()); - } - - private void checkStoreContents(int messageCount) - { - MessageCounter counter = new MessageCounter(); - _messageStore.newMessageStoreReader().visitMessages(counter); - - assertEquals("Message header count incorrect in the MetaDataMap", messageCount, counter.getCount()); - } - - private AMQShortString browse(AMQChannel channel, AMQQueue queue) throws Exception - { - FieldTable filters = new FieldTable(); - filters.put(AMQPFilterTypes.NO_CONSUME.getValue(), true); - - return channel.consumeFromSource(null, Collections.singleton(queue), true, filters, true, false); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/ReferenceCountingTest.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/ReferenceCountingTest.java deleted file mode 100644 index de3b68a0bc..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/ReferenceCountingTest.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.protocol.v0_8; - -import java.util.UUID; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.MessagePublishInfo; -import org.apache.qpid.server.message.EnqueueableMessage; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.store.MessageCounter; -import org.apache.qpid.server.store.MessageDurability; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.store.TestMemoryMessageStore; -import org.apache.qpid.server.store.Transaction; -import org.apache.qpid.server.store.TransactionLogResource; -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(null, false, false, null); - - final MessageMetaData mmd = new MessageMetaData(info, chb); - - StoredMessage storedMessage = _store.addMessage(mmd).allContentAdded(); - Transaction txn = _store.newTransaction(); - txn.enqueueMessage(createTransactionLogResource("dummyQ"), createEnqueueableMessage(storedMessage)); - txn.commitTran(); - AMQMessage message = new AMQMessage(storedMessage); - - MessageReference ref = message.newReference(); - - assertEquals(1, getStoreMessageCount()); - - ref.release(); - - assertEquals(0, getStoreMessageCount()); - } - - private int getStoreMessageCount() - { - MessageCounter counter = new MessageCounter(); - _store.newMessageStoreReader().visitMessages(counter); - return counter.getCount(); - } - - private ContentHeaderBody createPersistentContentHeader() - { - BasicContentHeaderProperties bchp = new BasicContentHeaderProperties(); - bchp.setDeliveryMode((byte)2); - ContentHeaderBody chb = new ContentHeaderBody(bchp); - return chb; - } - - public void testMessageRemains() throws AMQException - { - - MessagePublishInfo info = new MessagePublishInfo(null, false, false, null); - - final ContentHeaderBody chb = createPersistentContentHeader(); - - final MessageMetaData mmd = new MessageMetaData(info, chb); - - StoredMessage storedMessage = _store.addMessage(mmd).allContentAdded(); - Transaction txn = _store.newTransaction(); - txn.enqueueMessage(createTransactionLogResource("dummyQ"), createEnqueueableMessage(storedMessage)); - txn.commitTran(); - AMQMessage message = new AMQMessage(storedMessage); - - - MessageReference ref = message.newReference(); - - assertEquals(1, getStoreMessageCount()); - MessageReference ref2 = message.newReference(); - ref.release(); - assertEquals(1, getStoreMessageCount()); - } - - private TransactionLogResource createTransactionLogResource(final String queueName) - { - return new TransactionLogResource() - { - @Override - public String getName() - { - return queueName; - } - - @Override - public UUID getId() - { - return UUID.nameUUIDFromBytes(queueName.getBytes()); - } - - @Override - public MessageDurability getMessageDurability() - { - return MessageDurability.DEFAULT; - } - }; - } - - private EnqueueableMessage createEnqueueableMessage(final StoredMessage storedMessage) - { - return new EnqueueableMessage() - { - @Override - public long getMessageNumber() - { - return storedMessage.getMessageNumber(); - } - - @Override - public boolean isPersistent() - { - return true; - } - - @Override - public StoredMessage getStoredMessage() - { - return storedMessage; - } - }; - } - - public static junit.framework.Test suite() - { - return new junit.framework.TestSuite(ReferenceCountingTest.class); - } -} diff --git a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/UnacknowledgedMessageMapTest.java b/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/UnacknowledgedMessageMapTest.java deleted file mode 100644 index ca52173e66..0000000000 --- a/qpid/java/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/UnacknowledgedMessageMapTest.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.protocol.v0_8; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.Collection; - -import junit.framework.TestCase; - -import org.apache.qpid.server.message.MessageInstance; - -public class UnacknowledgedMessageMapTest extends TestCase -{ - public void testDeletedMessagesCantBeAcknowledged() - { - UnacknowledgedMessageMap map = new UnacknowledgedMessageMapImpl(100); - final int expectedSize = 5; - MessageInstance[] msgs = populateMap(map,expectedSize); - assertEquals(expectedSize,map.size()); - Collection acknowledged = map.acknowledge(100, true); - assertEquals(expectedSize, acknowledged.size()); - assertEquals(0,map.size()); - for(int i = 0; i < expectedSize; i++) - { - assertTrue("Message " + i + " is missing", acknowledged.contains(msgs[i])); - } - - map = new UnacknowledgedMessageMapImpl(100); - msgs = populateMap(map,expectedSize); - // simulate some messages being ttl expired - when(msgs[2].lockAcquisition()).thenReturn(Boolean.FALSE); - when(msgs[4].lockAcquisition()).thenReturn(Boolean.FALSE); - - assertEquals(expectedSize,map.size()); - - - acknowledged = map.acknowledge(100, true); - assertEquals(expectedSize-2, acknowledged.size()); - assertEquals(0,map.size()); - for(int i = 0; i < expectedSize; i++) - { - assertEquals(i != 2 && i != 4, acknowledged.contains(msgs[i])); - } - - } - - public MessageInstance[] populateMap(final UnacknowledgedMessageMap map, int size) - { - MessageInstance[] msgs = new MessageInstance[size]; - for(int i = 0; i < size; i++) - { - msgs[i] = createMessageInstance(i); - map.add((long)i,msgs[i]); - } - return msgs; - } - - private MessageInstance createMessageInstance(final int id) - { - MessageInstance instance = mock(MessageInstance.class); - when(instance.lockAcquisition()).thenReturn(Boolean.TRUE); - return instance; - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/pom.xml b/qpid/java/broker-plugins/amqp-1-0-protocol/pom.xml deleted file mode 100644 index 7242cb122a..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/pom.xml +++ /dev/null @@ -1,64 +0,0 @@ - - - - 4.0.0 - - - org.apache.qpid - qpid-java-build - 0.32-SNAPSHOT - ../../pom.xml - - - qpid-broker-plugins-amqp-1-0-protocol - Qpid AMQP 1-0 Protocol Broker Plug-in - AMQP 1-0 protocol broker plug-in - - - - org.apache.qpid - qpid-broker-core - ${project.version} - provided - - - - org.apache.qpid - qpid-broker-codegen - ${project.version} - true - - - - org.apache.qpid - qpid-amqp-1-0-common - ${project.version} - - - - log4j - log4j - ${log4j-version} - - - - - - - - diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Connection_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Connection_1_0.java deleted file mode 100644 index d1254cb289..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Connection_1_0.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.server.protocol.v1_0; - -import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.CONNECTION_FORMAT; - -import java.net.SocketAddress; -import java.security.Principal; -import java.security.PrivilegedAction; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Queue; -import java.util.Set; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.CopyOnWriteArrayList; - -import javax.security.auth.Subject; - -import org.apache.qpid.amqp_1_0.transport.ConnectionEndpoint; -import org.apache.qpid.amqp_1_0.transport.ConnectionEventListener; -import org.apache.qpid.amqp_1_0.transport.LinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.SessionEndpoint; -import org.apache.qpid.amqp_1_0.transport.SessionEventListener; -import org.apache.qpid.amqp_1_0.type.transport.AmqpError; -import org.apache.qpid.amqp_1_0.type.transport.End; -import org.apache.qpid.amqp_1_0.type.transport.Error; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.connection.ConnectionPrincipal; -import org.apache.qpid.server.logging.LogSubject; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.protocol.AMQConnectionModel; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.protocol.SessionModelListener; -import org.apache.qpid.server.security.SubjectCreator; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; -import org.apache.qpid.server.stats.StatisticsCounter; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; - -public class Connection_1_0 implements ConnectionEventListener, AMQConnectionModel -{ - - private final AmqpPort _port; - private final Broker _broker; - private final SubjectCreator _subjectCreator; - private final ProtocolEngine_1_0_0_SASL _protocolEngine; - private VirtualHostImpl _vhost; - private final Transport _transport; - private final ConnectionEndpoint _conn; - private final long _connectionId; - private final Collection _sessions = Collections.synchronizedCollection(new ArrayList()); - private final Object _reference = new Object(); - private final Subject _subject = new Subject(); - - private final CopyOnWriteArrayList _sessionListeners = - new CopyOnWriteArrayList(); - - private final StatisticsCounter _messageDeliveryStatistics, _messageReceiptStatistics, _dataDeliveryStatistics, _dataReceiptStatistics; - - private final LogSubject _logSubject = new LogSubject() - { - @Override - public String toLogString() - { - return "[" + - MessageFormat.format(CONNECTION_FORMAT, - getConnectionId(), - getClientId(), - getRemoteAddressString(), - _vhost.getName()) - + "] "; - - } - }; - - private volatile boolean _stopped; - - - private List> _closeTasks = - Collections.synchronizedList(new ArrayList>()); - - private final Queue> _asyncTaskList = - new ConcurrentLinkedQueue<>(); - - - private boolean _closedOnOpen; - - - - public Connection_1_0(Broker broker, - ConnectionEndpoint conn, - long connectionId, - AmqpPort port, - Transport transport, - final SubjectCreator subjectCreator, - final ProtocolEngine_1_0_0_SASL protocolEngine) - { - _protocolEngine = protocolEngine; - _broker = broker; - _port = port; - _transport = transport; - _conn = conn; - _connectionId = connectionId; - _subject.getPrincipals().add(new ConnectionPrincipal(this)); - _subjectCreator = subjectCreator; - _messageDeliveryStatistics = new StatisticsCounter("messages-delivered-" + getConnectionId()); - _dataDeliveryStatistics = new StatisticsCounter("data-delivered-" + getConnectionId()); - _messageReceiptStatistics = new StatisticsCounter("messages-received-" + getConnectionId()); - _dataReceiptStatistics = new StatisticsCounter("data-received-" + getConnectionId()); - } - - public Object getReference() - { - return _reference; - } - - @Override - public void openReceived() - { - String host = _conn.getLocalHostname(); - _vhost = ((AmqpPort)_port).getVirtualHost(host); - if(_vhost == null) - { - final Error err = new Error(); - err.setCondition(AmqpError.NOT_FOUND); - err.setDescription("Unknown hostname in connection open: '" + host + "'"); - _conn.close(err); - _closedOnOpen = true; - } - else - { - _vhost.getConnectionRegistry().registerConnection(this); - Subject authSubject = _subjectCreator.createSubjectWithGroups(_conn.getUser()); - _subject.getPrincipals().addAll(authSubject.getPrincipals()); - _subject.getPublicCredentials().addAll(authSubject.getPublicCredentials()); - _subject.getPrivateCredentials().addAll(authSubject.getPrivateCredentials()); - } - } - public void remoteSessionCreation(SessionEndpoint endpoint) - { - if(!_closedOnOpen) - { - final Session_1_0 session = new Session_1_0(this, endpoint); - _sessions.add(session); - sessionAdded(session); - endpoint.setSessionEventListener(new SessionEventListener() - { - @Override - public void remoteLinkCreation(final LinkEndpoint endpoint) - { - Subject.doAs(session.getSubject(), new PrivilegedAction() - { - @Override - public Object run() - { - session.remoteLinkCreation(endpoint); - return null; - } - }); - } - - @Override - public void remoteEnd(final End end) - { - Subject.doAs(session.getSubject(), new PrivilegedAction() - { - @Override - public Object run() - { - session.remoteEnd(end); - return null; - } - }); - } - }); - } - } - - void sessionEnded(Session_1_0 session) - { - if(!_closedOnOpen) - { - - _sessions.remove(session); - sessionRemoved(session); - } - } - - public void removeDeleteTask(final Action task) - { - _closeTasks.remove( task ); - } - - public void addDeleteTask(final Action task) - { - _closeTasks.add( task ); - } - - private void addAsyncTask(final Action action) - { - _asyncTaskList.add(action); - notifyWork(); - } - - - public void closeReceived() - { - Collection sessions = new ArrayList(_sessions); - - for(Session_1_0 session : sessions) - { - session.remoteEnd(new End()); - } - - List> taskCopy; - - synchronized (_closeTasks) - { - taskCopy = new ArrayList>(_closeTasks); - } - for(Action task : taskCopy) - { - task.performAction(this); - } - synchronized (_closeTasks) - { - _closeTasks.clear(); - } - if(_vhost != null) - { - _vhost.getConnectionRegistry().deregisterConnection(this); - } - - - } - - public void closed() - { - closeReceived(); - } - - - @Override - public void closeAsync(AMQConstant cause, String message) - { - Action action = new Action() - { - @Override - public void performAction(final Connection_1_0 object) - { - _conn.close(); - - } - }; - addAsyncTask(action); - - } - - @Override - public void block() - { - // TODO - } - - @Override - public void unblock() - { - // TODO - } - - @Override - public void closeSessionAsync(final Session_1_0 session, final AMQConstant cause, final String message) - { - addAsyncTask(new Action() - { - @Override - public void performAction(final Connection_1_0 object) - { - session.close(cause, message); - } - }); - } - - @Override - public long getConnectionId() - { - return _connectionId; - } - - @Override - public List getSessionModels() - { - return new ArrayList(_sessions); - } - - @Override - public LogSubject getLogSubject() - { - return _logSubject; - } - - @Override - public String getRemoteAddressString() - { - return String.valueOf(_conn.getRemoteAddress()); - } - - public SocketAddress getRemoteAddress() - { - return _conn.getRemoteAddress(); - } - - @Override - public String getRemoteProcessPid() - { - return null; // TODO - } - - @Override - public String getClientId() - { - return _conn.getRemoteContainerId(); - } - - @Override - public String getRemoteContainerName() - { - return _conn.getRemoteContainerId(); - } - - @Override - public String getClientVersion() - { - return ""; //TODO - } - - @Override - public String getClientProduct() - { - return ""; //TODO - } - - public Principal getAuthorizedPrincipal() - { - Set authPrincipals = _subject.getPrincipals(AuthenticatedPrincipal.class); - return authPrincipals.isEmpty() ? null : authPrincipals.iterator().next(); - } - - @Override - public long getSessionCountLimit() - { - return 0; // TODO - } - - @Override - public long getLastIoTime() - { - return 0; // TODO - } - - @Override - public String getVirtualHostName() - { - return _vhost == null ? null : _vhost.getName(); - } - - @Override - public AmqpPort getPort() - { - return _port; - } - - public ServerProtocolEngine getProtocolEngine() - { - return _protocolEngine; - } - - @Override - public Transport getTransport() - { - return _transport; - } - - @Override - public void stop() - { - _stopped = true; - } - - @Override - public boolean isStopped() - { - return _stopped; - } - - @Override - public void registerMessageReceived(long messageSize, long timestamp) - { - _messageReceiptStatistics.registerEvent(1L, timestamp); - _dataReceiptStatistics.registerEvent(messageSize, timestamp); - _vhost.registerMessageReceived(messageSize,timestamp); - - } - - @Override - public void registerMessageDelivered(long messageSize) - { - - _messageDeliveryStatistics.registerEvent(1L); - _dataDeliveryStatistics.registerEvent(messageSize); - _vhost.registerMessageDelivered(messageSize); - } - - @Override - public StatisticsCounter getMessageDeliveryStatistics() - { - return _messageDeliveryStatistics; - } - - @Override - public StatisticsCounter getMessageReceiptStatistics() - { - return _messageReceiptStatistics; - } - - @Override - public StatisticsCounter getDataDeliveryStatistics() - { - return _dataDeliveryStatistics; - } - - @Override - public StatisticsCounter getDataReceiptStatistics() - { - return _dataReceiptStatistics; - } - - @Override - public void resetStatistics() - { - _dataDeliveryStatistics.reset(); - _dataReceiptStatistics.reset(); - _messageDeliveryStatistics.reset(); - _messageReceiptStatistics.reset(); - } - - - - AMQConnectionModel getModel() - { - return this; - } - - - Subject getSubject() - { - return _subject; - } - - public VirtualHostImpl getVirtualHost() - { - return _vhost; - } - - - @Override - public void addSessionListener(final SessionModelListener listener) - { - _sessionListeners.add(listener); - } - - @Override - public void removeSessionListener(final SessionModelListener listener) - { - _sessionListeners.remove(listener); - } - - private void sessionAdded(final AMQSessionModel session) - { - for(SessionModelListener l : _sessionListeners) - { - l.sessionAdded(session); - } - } - - private void sessionRemoved(final AMQSessionModel session) - { - for(SessionModelListener l : _sessionListeners) - { - l.sessionRemoved(session); - } - } - - - public void transportStateChanged() - { - for (Session_1_0 session : _sessions) - { - session.transportStateChanged(); - } - } - - @Override - public void notifyWork() - { - _protocolEngine.notifyWork(); - } - - @Override - public boolean isMessageAssignmentSuspended() - { - return _protocolEngine.isMessageAssignmentSuspended(); - } - - public void processPending() - { - for (AMQSessionModel session : getSessionModels()) - { - session.processPending(); - } - - while(_asyncTaskList.peek() != null) - { - Action asyncAction = _asyncTaskList.poll(); - asyncAction.performAction(this); - } - - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ConsumerTarget_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ConsumerTarget_1_0.java deleted file mode 100644 index 680c05ec0a..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ConsumerTarget_1_0.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.protocol.v1_0; - -import java.nio.ByteBuffer; -import java.util.List; - -import org.apache.qpid.amqp_1_0.codec.ValueHandler; -import org.apache.qpid.amqp_1_0.messaging.SectionEncoder; -import org.apache.qpid.amqp_1_0.messaging.SectionEncoderImpl; -import org.apache.qpid.amqp_1_0.transport.SendingLinkEndpoint; -import org.apache.qpid.amqp_1_0.type.AmqpErrorException; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.DeliveryState; -import org.apache.qpid.amqp_1_0.type.Outcome; -import org.apache.qpid.amqp_1_0.type.UnsignedInteger; -import org.apache.qpid.amqp_1_0.type.codec.AMQPDescribedTypeRegistry; -import org.apache.qpid.amqp_1_0.type.messaging.Accepted; -import org.apache.qpid.amqp_1_0.type.messaging.Header; -import org.apache.qpid.amqp_1_0.type.messaging.Modified; -import org.apache.qpid.amqp_1_0.type.messaging.Released; -import org.apache.qpid.amqp_1_0.type.transaction.TransactionalState; -import org.apache.qpid.amqp_1_0.type.transport.SenderSettleMode; -import org.apache.qpid.amqp_1_0.type.transport.Transfer; -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.consumer.AbstractConsumerTarget; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.protocol.LinkRegistry; -import org.apache.qpid.server.protocol.MessageConverterRegistry; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; - -class ConsumerTarget_1_0 extends AbstractConsumerTarget -{ - private final boolean _acquires; - private SendingLink_1_0 _link; - - private long _deliveryTag = 0L; - - private Binary _transactionId; - private final AMQPDescribedTypeRegistry _typeRegistry; - private final SectionEncoder _sectionEncoder; - private ConsumerImpl _consumer; - - public ConsumerTarget_1_0(final SendingLink_1_0 link, - boolean acquires) - { - super(State.SUSPENDED); - _link = link; - _typeRegistry = link.getEndpoint().getSession().getConnection().getDescribedTypeRegistry(); - _sectionEncoder = new SectionEncoderImpl(_typeRegistry); - _acquires = acquires; - } - - public ConsumerImpl getConsumer() - { - return _consumer; - } - - private SendingLinkEndpoint getEndpoint() - { - return _link.getEndpoint(); - } - - @Override - public boolean doIsSuspended() - { - return _link.getSession().getConnectionModel().isStopped() || getState() != State.ACTIVE; - - } - - public boolean close() - { - boolean closed = false; - State state = getState(); - - getSendLock(); - try - { - while(!closed && state != State.CLOSED) - { - closed = updateState(state, State.CLOSED); - if(!closed) - { - state = getState(); - } - } - return closed; - } - finally - { - releaseSendLock(); - } - } - - public void doSend(final ConsumerImpl consumer, final MessageInstance entry, boolean batch) - { - // TODO - ServerMessage serverMessage = entry.getMessage(); - Message_1_0 message; - if(serverMessage instanceof Message_1_0) - { - message = (Message_1_0) serverMessage; - } - else - { - final MessageConverter converter = MessageConverterRegistry.getConverter(serverMessage.getClass(), Message_1_0.class); - message = (Message_1_0) converter.convert(serverMessage, _link.getVirtualHost()); - } - - Transfer transfer = new Transfer(); - //TODO - - - List fragments = message.getFragments(); - ByteBuffer payload; - if(fragments.size() == 1) - { - payload = fragments.get(0); - } - else - { - int size = 0; - for(ByteBuffer fragment : fragments) - { - size += fragment.remaining(); - } - - payload = ByteBuffer.allocate(size); - - for(ByteBuffer fragment : fragments) - { - payload.put(fragment.duplicate()); - } - - payload.flip(); - } - - if(entry.getDeliveryCount() != 0) - { - payload = payload.duplicate(); - ValueHandler valueHandler = new ValueHandler(_typeRegistry); - - Header oldHeader = null; - try - { - ByteBuffer encodedBuf = payload.duplicate(); - Object value = valueHandler.parse(payload); - if(value instanceof Header) - { - oldHeader = (Header) value; - } - else - { - payload.position(0); - } - } - catch (AmqpErrorException e) - { - //TODO - throw new ConnectionScopedRuntimeException(e); - } - - Header header = new Header(); - if(oldHeader != null) - { - header.setDurable(oldHeader.getDurable()); - header.setPriority(oldHeader.getPriority()); - header.setTtl(oldHeader.getTtl()); - } - header.setDeliveryCount(UnsignedInteger.valueOf(entry.getDeliveryCount())); - _sectionEncoder.reset(); - _sectionEncoder.encodeObject(header); - Binary encodedHeader = _sectionEncoder.getEncoding(); - - ByteBuffer oldPayload = payload; - payload = ByteBuffer.allocate(oldPayload.remaining() + encodedHeader.getLength()); - payload.put(encodedHeader.getArray(),encodedHeader.getArrayOffset(),encodedHeader.getLength()); - payload.put(oldPayload); - payload.flip(); - } - - transfer.setPayload(payload); - byte[] data = new byte[8]; - ByteBuffer.wrap(data).putLong(_deliveryTag++); - final Binary tag = new Binary(data); - - transfer.setDeliveryTag(tag); - - synchronized(_link.getLock()) - { - if(_link.isAttached()) - { - if(SenderSettleMode.SETTLED.equals(getEndpoint().getSendingSettlementMode())) - { - transfer.setSettled(true); - } - else - { - UnsettledAction action = _acquires - ? new DispositionAction(tag, entry) - : new DoNothingAction(tag, entry); - - _link.addUnsettled(tag, action, entry); - } - - if(_transactionId != null) - { - TransactionalState state = new TransactionalState(); - state.setTxnId(_transactionId); - transfer.setState(state); - } - // TODO - need to deal with failure here - if(_acquires && _transactionId != null) - { - ServerTransaction txn = _link.getTransaction(_transactionId); - if(txn != null) - { - txn.addPostTransactionAction(new ServerTransaction.Action(){ - - public void postCommit() - { - //To change body of implemented methods use File | Settings | File Templates. - } - - public void onRollback() - { - if(entry.isAcquiredBy(getConsumer())) - { - entry.release(); - _link.getEndpoint().updateDisposition(tag, (DeliveryState)null, true); - - - } - } - }); - } - - } - getSession().getConnectionModel().registerMessageDelivered(message.getSize()); - getEndpoint().transfer(transfer); - } - else - { - entry.release(); - } - } - - } - - public void flushBatched() - { - // TODO - } - - public void queueDeleted() - { - //TODO - getEndpoint().setSource(null); - getEndpoint().close(); - - final LinkRegistry linkReg = getSession().getConnection() - .getVirtualHost() - .getLinkRegistry(getEndpoint().getSession().getConnection().getRemoteContainerId()); - linkReg.unregisterSendingLink(getEndpoint().getName()); - } - - public boolean allocateCredit(final ServerMessage msg) - { - synchronized (_link.getLock()) - { - - ServerProtocolEngine protocolEngine = getSession().getConnection().getProtocolEngine(); - final boolean hasCredit = _link.isAttached() && getEndpoint().hasCreditToSend() && !protocolEngine.isTransportBlockedForWriting(); - if(!hasCredit && getState() == State.ACTIVE) - { - suspend(); - } - - return hasCredit; - } - } - - - public void suspend() - { - synchronized(_link.getLock()) - { - updateState(State.ACTIVE, State.SUSPENDED); - } - } - - - public void restoreCredit(final ServerMessage message) - { - //TODO - } - - public void queueEmpty() - { - synchronized(_link.getLock()) - { - if(_link.drained()) - { - updateState(State.ACTIVE, State.SUSPENDED); - } - } - } - - public void flowStateChanged() - { - synchronized(_link.getLock()) - { - ServerProtocolEngine protocolEngine = getSession().getConnection().getProtocolEngine(); - if(isSuspended() && getEndpoint() != null && !protocolEngine.isTransportBlockedForWriting()) - { - updateState(State.SUSPENDED, State.ACTIVE); - _transactionId = _link.getTransactionId(); - } - } - } - - public Session_1_0 getSession() - { - return _link.getSession(); - } - - public void flush() - { - _consumer.flush(); - } - - private class DispositionAction implements UnsettledAction - { - - private final MessageInstance _queueEntry; - private final Binary _deliveryTag; - - public DispositionAction(Binary tag, MessageInstance queueEntry) - { - _deliveryTag = tag; - _queueEntry = queueEntry; - } - - public boolean process(DeliveryState state, final Boolean settled) - { - - Binary transactionId = null; - final Outcome outcome; - // If disposition is settled this overrides the txn? - if(state instanceof TransactionalState) - { - transactionId = ((TransactionalState)state).getTxnId(); - outcome = ((TransactionalState)state).getOutcome(); - } - else if (state instanceof Outcome) - { - outcome = (Outcome) state; - } - else - { - outcome = null; - } - - - ServerTransaction txn = _link.getTransaction(transactionId); - - if(outcome instanceof Accepted) - { - _queueEntry.lockAcquisition(); - txn.dequeue(_queueEntry.getEnqueueRecord(), - new ServerTransaction.Action() - { - - public void postCommit() - { - if(_queueEntry.isAcquiredBy(getConsumer())) - { - _queueEntry.delete(); - } - } - - public void onRollback() - { - - } - }); - txn.addPostTransactionAction(new ServerTransaction.Action() - { - public void postCommit() - { - //_link.getEndpoint().settle(_deliveryTag); - _link.getEndpoint().updateDisposition(_deliveryTag, (DeliveryState)outcome, true); - _link.getEndpoint().sendFlowConditional(); - } - - public void onRollback() - { - if(Boolean.TRUE.equals(settled)) - { - final Modified modified = new Modified(); - modified.setDeliveryFailed(true); - _link.getEndpoint().updateDisposition(_deliveryTag, modified, true); - _link.getEndpoint().sendFlowConditional(); - _queueEntry.incrementDeliveryCount(); - _queueEntry.release(); - } - } - }); - } - else if(outcome instanceof Released) - { - txn.addPostTransactionAction(new ServerTransaction.Action() - { - public void postCommit() - { - - _queueEntry.release(); - _link.getEndpoint().settle(_deliveryTag); - } - - public void onRollback() - { - _link.getEndpoint().settle(_deliveryTag); - } - }); - } - - else if(outcome instanceof Modified) - { - txn.addPostTransactionAction(new ServerTransaction.Action() - { - public void postCommit() - { - - _queueEntry.release(); - if(Boolean.TRUE.equals(((Modified)outcome).getDeliveryFailed())) - { - _queueEntry.incrementDeliveryCount(); - } - _link.getEndpoint().settle(_deliveryTag); - } - - public void onRollback() - { - if(Boolean.TRUE.equals(settled)) - { - final Modified modified = new Modified(); - modified.setDeliveryFailed(true); - _link.getEndpoint().updateDisposition(_deliveryTag, modified, true); - _link.getEndpoint().sendFlowConditional(); - } - } - }); - } - - return (transactionId == null && outcome != null); - } - } - - private class DoNothingAction implements UnsettledAction - { - public DoNothingAction(final Binary tag, - final MessageInstance queueEntry) - { - } - - public boolean process(final DeliveryState state, final Boolean settled) - { - Binary transactionId = null; - Outcome outcome = null; - // If disposition is settled this overrides the txn? - if(state instanceof TransactionalState) - { - transactionId = ((TransactionalState)state).getTxnId(); - outcome = ((TransactionalState)state).getOutcome(); - } - else if (state instanceof Outcome) - { - outcome = (Outcome) state; - } - return true; - } - } - - @Override - public AMQSessionModel getSessionModel() - { - return getSession(); - } - - @Override - public void acquisitionRemoved(final MessageInstance node) - { - } - - @Override - public void consumerAdded(final ConsumerImpl sub) - { - _consumer = sub; - } - - @Override - public void consumerRemoved(final ConsumerImpl sub) - { - close(); - } - - @Override - public long getUnacknowledgedBytes() - { - // TODO - return 0; - } - - @Override - public long getUnacknowledgedMessages() - { - // TODO - return 0; - } - - @Override - protected void processClosed() - { - - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Destination.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Destination.java deleted file mode 100644 index d45758391c..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Destination.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.protocol.v1_0; - - -public interface Destination -{ - - -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ExchangeDestination.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ExchangeDestination.java deleted file mode 100644 index b842c44a16..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ExchangeDestination.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.protocol.v1_0; - -import org.apache.qpid.amqp_1_0.type.Outcome; -import org.apache.qpid.amqp_1_0.type.messaging.Accepted; -import org.apache.qpid.amqp_1_0.type.messaging.Rejected; -import org.apache.qpid.amqp_1_0.type.messaging.TerminusDurability; -import org.apache.qpid.amqp_1_0.type.messaging.TerminusExpiryPolicy; -import org.apache.qpid.server.exchange.ExchangeImpl; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.txn.ServerTransaction; - -public class ExchangeDestination implements ReceivingDestination, SendingDestination -{ - private static final Accepted ACCEPTED = new Accepted(); - public static final Rejected REJECTED = new Rejected(); - private static final Outcome[] OUTCOMES = { ACCEPTED, REJECTED}; - - private ExchangeImpl _exchange; - private TerminusDurability _durability; - private TerminusExpiryPolicy _expiryPolicy; - private String _initialRoutingAddress; - - public ExchangeDestination(ExchangeImpl exchange, TerminusDurability durable, TerminusExpiryPolicy expiryPolicy) - { - _exchange = exchange; - _durability = durable; - _expiryPolicy = expiryPolicy; - } - - public Outcome[] getOutcomes() - { - return OUTCOMES; - } - - public Outcome send(final Message_1_0 message, ServerTransaction txn) - { - final InstanceProperties instanceProperties = - new InstanceProperties() - { - - @Override - public Object getProperty(final Property prop) - { - switch(prop) - { - case MANDATORY: - return false; - case REDELIVERED: - return false; - case PERSISTENT: - return message.isPersistent(); - case IMMEDIATE: - return false; - case EXPIRATION: - return message.getExpiration(); - } - return null; - }}; - - String routingAddress; - MessageMetaData_1_0.MessageHeader_1_0 messageHeader = message.getMessageHeader(); - if(_initialRoutingAddress == null) - { - routingAddress = messageHeader.getSubject(); - if(routingAddress == null) - { - if (messageHeader.getHeader("routing-key") instanceof String) - { - routingAddress = (String) messageHeader.getHeader("routing-key"); - } - else if (messageHeader.getHeader("routing_key") instanceof String) - { - routingAddress = (String) messageHeader.getHeader("routing_key"); - } - else if (messageHeader.getTo() != null - && messageHeader.getTo().startsWith(_exchange.getName() + "/")) - { - routingAddress = messageHeader.getTo().substring(1+_exchange.getName().length()); - } - else - { - routingAddress = ""; - } - } - } - else - { - if (messageHeader.getTo() != null - && messageHeader.getTo().startsWith(_exchange.getName() + "/" + _initialRoutingAddress + "/")) - { - routingAddress = messageHeader.getTo().substring(2+_exchange.getName().length()+_initialRoutingAddress.length()); - } - else - { - routingAddress = _initialRoutingAddress; - } - } - int enqueues = _exchange.send(message, - routingAddress, - instanceProperties, - txn, - null); - - - return enqueues == 0 ? REJECTED : ACCEPTED; - } - - TerminusDurability getDurability() - { - return _durability; - } - - TerminusExpiryPolicy getExpiryPolicy() - { - return _expiryPolicy; - } - - public int getCredit() - { - // TODO - fix - return 20000; - } - - public ExchangeImpl getExchange() - { - return _exchange; - } - - public void setInitialRoutingAddress(final String initialRoutingAddress) - { - _initialRoutingAddress = initialRoutingAddress; - } - - public String getInitialRoutingAddress() - { - return _initialRoutingAddress; - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Link_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Link_1_0.java deleted file mode 100644 index 5ce24f406d..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Link_1_0.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.protocol.v1_0; - -import org.apache.qpid.server.protocol.LinkModel; - -public interface Link_1_0 extends LinkModel -{ - void start(); -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_Internal_to_v1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_Internal_to_v1_0.java deleted file mode 100644 index 0a6fec1200..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_Internal_to_v1_0.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.protocol.v1_0; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; - -import org.apache.qpid.amqp_1_0.messaging.SectionEncoder; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.Section; -import org.apache.qpid.amqp_1_0.type.UnsignedByte; -import org.apache.qpid.amqp_1_0.type.UnsignedInteger; -import org.apache.qpid.amqp_1_0.type.messaging.AmqpValue; -import org.apache.qpid.amqp_1_0.type.messaging.ApplicationProperties; -import org.apache.qpid.amqp_1_0.type.messaging.Data; -import org.apache.qpid.amqp_1_0.type.messaging.Header; -import org.apache.qpid.amqp_1_0.type.messaging.Properties; -import org.apache.qpid.server.message.internal.InternalMessage; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; - -@PluggableService -public class MessageConverter_Internal_to_v1_0 extends MessageConverter_to_1_0 -{ - private static final Charset UTF_8 = Charset.forName("UTF-8"); - - - public Class getInputClass() - { - return InternalMessage.class; - } - - - @Override - protected MessageMetaData_1_0 convertMetaData(final InternalMessage serverMessage, - final SectionEncoder sectionEncoder) - { - List
sections = new ArrayList
(3); - Header header = new Header(); - - header.setDurable(serverMessage.isPersistent()); - header.setPriority(UnsignedByte.valueOf(serverMessage.getMessageHeader().getPriority())); - if(serverMessage.getExpiration() != 0l && serverMessage.getArrivalTime() !=0l && serverMessage.getExpiration() >= serverMessage.getArrivalTime()) - { - header.setTtl(UnsignedInteger.valueOf(serverMessage.getExpiration()-serverMessage.getArrivalTime())); - } - - sections.add(header); - - Properties properties = new Properties(); - properties.setCorrelationId(serverMessage.getMessageHeader().getCorrelationId()); - properties.setCreationTime(new Date(serverMessage.getMessageHeader().getTimestamp())); - properties.setMessageId(serverMessage.getMessageHeader().getMessageId()); - final String userId = serverMessage.getMessageHeader().getUserId(); - if(userId != null) - { - properties.setUserId(new Binary(userId.getBytes(UTF_8))); - } - properties.setReplyTo(serverMessage.getMessageHeader().getReplyTo()); - - sections.add(properties); - - if(!serverMessage.getMessageHeader().getHeaderNames().isEmpty()) - { - ApplicationProperties applicationProperties = new ApplicationProperties(serverMessage.getMessageHeader().getHeaderMap() ); - sections.add(applicationProperties); - } - return new MessageMetaData_1_0(sections, sectionEncoder); - - } - - protected Section getBodySection(final InternalMessage serverMessage, final String mimeType) - { - return convertToBody(serverMessage.getMessageBody()); - } - - - @Override - public String getType() - { - return "Internal to v1-0"; - } - - - public Section convertToBody(Object object) - { - if(object instanceof String) - { - return new AmqpValue(object); - } - else if(object instanceof byte[]) - { - return new Data(new Binary((byte[])object)); - } - else if(object instanceof Map) - { - return new AmqpValue(MessageConverter_to_1_0.fixMapValues((Map)object)); - } - else if(object instanceof List) - { - return new AmqpValue(MessageConverter_to_1_0.fixListValues((List)object)); - } - else - { - ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); - try - { - ObjectOutputStream os = new ObjectOutputStream(bytesOut); - os.writeObject(object); - return new Data(new Binary(bytesOut.toByteArray())); - } - catch (IOException e) - { - throw new ConnectionScopedRuntimeException(e); - } - } - } - -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_from_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_from_1_0.java deleted file mode 100644 index 266f3b6868..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_from_1_0.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.protocol.v1_0; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import org.apache.qpid.amqp_1_0.messaging.SectionDecoderImpl; -import org.apache.qpid.amqp_1_0.type.AmqpErrorException; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.Section; -import org.apache.qpid.amqp_1_0.type.Symbol; -import org.apache.qpid.amqp_1_0.type.UnsignedByte; -import org.apache.qpid.amqp_1_0.type.UnsignedInteger; -import org.apache.qpid.amqp_1_0.type.UnsignedLong; -import org.apache.qpid.amqp_1_0.type.UnsignedShort; -import org.apache.qpid.amqp_1_0.type.messaging.AmqpSequence; -import org.apache.qpid.amqp_1_0.type.messaging.AmqpValue; -import org.apache.qpid.amqp_1_0.type.messaging.Data; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.transport.codec.BBEncoder; -import org.apache.qpid.typedmessage.TypedBytesContentWriter; -import org.apache.qpid.typedmessage.TypedBytesFormatException; - -public class MessageConverter_from_1_0 -{ - private static final Charset UTF_8 = Charset.forName("UTF-8"); - - public static Object convertBodyToObject(final Message_1_0 serverMessage) - { - byte[] data = new byte[(int) serverMessage.getSize()]; - serverMessage.getStoredMessage().getContent(0, ByteBuffer.wrap(data)); - - SectionDecoderImpl sectionDecoder = new SectionDecoderImpl(MessageConverter_v1_0_to_Internal.TYPE_REGISTRY); - - Object bodyObject; - try - { - List
sections = sectionDecoder.parseAll(ByteBuffer.wrap(data)); - ListIterator
iterator = sections.listIterator(); - Section previousSection = null; - while(iterator.hasNext()) - { - Section section = iterator.next(); - if(!(section instanceof AmqpValue || section instanceof Data || section instanceof AmqpSequence)) - { - iterator.remove(); - } - else - { - if(previousSection != null && (previousSection.getClass() != section.getClass() || section instanceof AmqpValue)) - { - throw new ConnectionScopedRuntimeException("Message is badly formed and has multiple body section which are not all Data or not all AmqpSequence"); - } - else - { - previousSection = section; - } - } - } - - - if(sections.isEmpty()) - { - // should actually be illegal - bodyObject = new byte[0]; - } - else - { - Section firstBodySection = sections.get(0); - if(firstBodySection instanceof AmqpValue) - { - bodyObject = convertValue(((AmqpValue)firstBodySection).getValue()); - } - else if(firstBodySection instanceof Data) - { - int totalSize = 0; - for(Section section : sections) - { - totalSize += ((Data)section).getValue().getLength(); - } - byte[] bodyData = new byte[totalSize]; - ByteBuffer buf = ByteBuffer.wrap(bodyData); - for(Section section : sections) - { - buf.put(((Data)section).getValue().asByteBuffer()); - } - bodyObject = bodyData; - } - else - { - ArrayList totalSequence = new ArrayList(); - for(Section section : sections) - { - totalSequence.addAll(((AmqpSequence)section).getValue()); - } - bodyObject = convertValue(totalSequence); - } - } - - } - catch (AmqpErrorException e) - { - throw new ConnectionScopedRuntimeException(e); - } - return bodyObject; - } - - private static final Set STANDARD_TYPES = new HashSet<>(Arrays.asList(Boolean.class, - Byte.class, - Short.class, - Integer.class, - Long.class, - Float.class, - Double.class, - Character.class, - String.class, - byte[].class, - UUID.class)); - - private static Map convertMap(final Map map) - { - Map resultMap = new LinkedHashMap(); - Iterator iterator = map.entrySet().iterator(); - while(iterator.hasNext()) - { - Map.Entry entry = iterator.next(); - resultMap.put(convertValue(entry.getKey()), convertValue(entry.getValue())); - - } - return resultMap; - } - - public static Object convertValue(final Object value) - { - if(value != null && !STANDARD_TYPES.contains(value)) - { - if(value instanceof Map) - { - return convertMap((Map)value); - } - else if(value instanceof List) - { - return convertList((List)value); - } - else if(value instanceof UnsignedByte) - { - return ((UnsignedByte)value).shortValue(); - } - else if(value instanceof UnsignedShort) - { - return ((UnsignedShort)value).intValue(); - } - else if(value instanceof UnsignedInteger) - { - return ((UnsignedInteger)value).longValue(); - } - else if(value instanceof UnsignedLong) - { - return ((UnsignedLong)value).longValue(); - } - else if(value instanceof Symbol) - { - return value.toString(); - } - else if(value instanceof Date) - { - return ((Date)value).getTime(); - } - else if(value instanceof Binary) - { - Binary binary = (Binary)value; - byte[] data = new byte[binary.getLength()]; - binary.asByteBuffer().get(data); - return data; - } - else - { - // Throw exception instead? - return value.toString(); - } - } - else - { - return value; - } - } - - private static List convertList(final List list) - { - List result = new ArrayList(list.size()); - for(Object entry : list) - { - result.add(convertValue(entry)); - } - return result; - } - - public static byte[] convertToBody(Object object) - { - if(object instanceof String) - { - return ((String)object).getBytes(UTF_8); - } - else if(object instanceof byte[]) - { - return (byte[]) object; - } - else if(object instanceof Map) - { - BBEncoder encoder = new BBEncoder(1024); - encoder.writeMap((Map)object); - ByteBuffer buf = encoder.segment(); - int remaining = buf.remaining(); - byte[] data = new byte[remaining]; - buf.get(data); - return data; - - } - else if(object instanceof List) - { - try - { - ByteBuffer buf; - if(onlyPrimitiveTypes((List)object)) - { - TypedBytesContentWriter writer = new TypedBytesContentWriter(); - for(Object value : (List)object) - { - writer.writeObject(value); - } - buf = writer.getData(); - - } - else - { - BBEncoder encoder = new BBEncoder(1024); - encoder.writeList((List) object); - buf = encoder.segment(); - } - int remaining = buf.remaining(); - byte[] data = new byte[remaining]; - buf.get(data); - return data; - } - catch (TypedBytesFormatException e) - { - throw new ConnectionScopedRuntimeException(e); - } - } - else - { - ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); - try - { - ObjectOutputStream os = new ObjectOutputStream(bytesOut); - os.writeObject(object); - return bytesOut.toByteArray(); - } - catch (IOException e) - { - throw new ConnectionScopedRuntimeException(e); - } - } - } - - public static boolean onlyPrimitiveTypes(final List list) - { - for(Object value : list) - { - if(!(value instanceof String - || value instanceof Integer - || value instanceof Long - || value instanceof Double - || value instanceof Float - || value instanceof Byte - || value instanceof Short - || value instanceof Character - || value instanceof Boolean - || value instanceof byte[])) - { - return false; - } - } - return true; - } - - public static String getBodyMimeType(Object object) - { - if(object instanceof String) - { - return "text/plain"; - } - else if(object instanceof byte[]) - { - return "application/octet-stream"; - } - else if(object instanceof Map) - { - return "amqp/map"; - } - else if(object instanceof List) - { - return onlyPrimitiveTypes((List)object) ? "jms/stream-message" : "amqp/list"; - } - else - { - return "application/java-object-stream"; - } - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_to_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_to_1_0.java deleted file mode 100644 index e9e81bb623..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_to_1_0.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.server.protocol.v1_0; - -import java.io.EOFException; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; - -import org.apache.qpid.amqp_1_0.messaging.SectionEncoder; -import org.apache.qpid.amqp_1_0.messaging.SectionEncoderImpl; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.Section; -import org.apache.qpid.amqp_1_0.type.Symbol; -import org.apache.qpid.amqp_1_0.type.codec.AMQPDescribedTypeRegistry; -import org.apache.qpid.amqp_1_0.type.messaging.AmqpValue; -import org.apache.qpid.amqp_1_0.type.messaging.Data; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.codec.BBDecoder; -import org.apache.qpid.typedmessage.TypedBytesContentReader; -import org.apache.qpid.typedmessage.TypedBytesFormatException; -import org.apache.qpid.util.GZIPUtils; - -public abstract class MessageConverter_to_1_0 implements MessageConverter -{ - private final AMQPDescribedTypeRegistry _typeRegistry = AMQPDescribedTypeRegistry.newInstance() - .registerTransportLayer() - .registerMessagingLayer() - .registerTransactionLayer() - .registerSecurityLayer(); - - @Override - public final Class getOutputClass() - { - return Message_1_0.class; - } - - @Override - public final Message_1_0 convert(M message, VirtualHostImpl vhost) - { - - SectionEncoder sectionEncoder = new SectionEncoderImpl(_typeRegistry); - return new Message_1_0(convertToStoredMessage(message, sectionEncoder)); - } - - - private StoredMessage convertToStoredMessage(final M serverMessage, SectionEncoder sectionEncoder) - { - final MessageMetaData_1_0 metaData = convertMetaData(serverMessage, sectionEncoder); - return convertServerMessage(metaData, serverMessage, sectionEncoder); - } - - abstract protected MessageMetaData_1_0 convertMetaData(final M serverMessage, SectionEncoder sectionEncoder); - - - private static Section convertMessageBody(String mimeType, byte[] data) - { - if("text/plain".equals(mimeType) || "text/xml".equals(mimeType)) - { - String text = new String(data); - return new AmqpValue(text); - } - else if("jms/map-message".equals(mimeType)) - { - TypedBytesContentReader reader = new TypedBytesContentReader(ByteBuffer.wrap(data)); - - LinkedHashMap map = new LinkedHashMap(); - final int entries = reader.readIntImpl(); - for (int i = 0; i < entries; i++) - { - try - { - String propName = reader.readStringImpl(); - Object value = reader.readObject(); - - map.put(propName, value); - } - catch (EOFException e) - { - throw new IllegalArgumentException(e); - } - catch (TypedBytesFormatException e) - { - throw new IllegalArgumentException(e); - } - - } - - return new AmqpValue(fixMapValues(map)); - - } - else if("amqp/map".equals(mimeType)) - { - BBDecoder decoder = new BBDecoder(); - decoder.init(ByteBuffer.wrap(data)); - final Map map = decoder.readMap(); - - return new AmqpValue(fixMapValues(map)); - - } - else if("amqp/list".equals(mimeType)) - { - BBDecoder decoder = new BBDecoder(); - decoder.init(ByteBuffer.wrap(data)); - return new AmqpValue(fixListValues(decoder.readList())); - } - else if("jms/stream-message".equals(mimeType)) - { - TypedBytesContentReader reader = new TypedBytesContentReader(ByteBuffer.wrap(data)); - - List list = new ArrayList(); - while (reader.remaining() != 0) - { - try - { - list.add(fixValue(reader.readObject())); - } - catch (TypedBytesFormatException e) - { - throw new ConnectionScopedRuntimeException(e); - } - catch (EOFException e) - { - throw new ConnectionScopedRuntimeException(e); - } - } - return new AmqpValue(list); - } - else - { - return new Data(new Binary(data)); - - } - } - - static Map fixMapValues(final Map map) - { - for(Map.Entry entry : map.entrySet()) - { - entry.setValue(fixValue(entry.getValue())); - } - return map; - } - - static Object fixValue(final Object value) - { - if(value instanceof byte[]) - { - return new Binary((byte[])value); - } - else if(value instanceof Map) - { - return fixMapValues((Map)value); - } - else if(value instanceof List) - { - return fixListValues((List)value); - } - else - { - return value; - } - } - - static List fixListValues(final List list) - { - ListIterator iterator = list.listIterator(); - while(iterator.hasNext()) - { - Object value = iterator.next(); - iterator.set(fixValue(value)); - - } - return list; - } - - private StoredMessage convertServerMessage(final MessageMetaData_1_0 metaData, - final M serverMessage, - SectionEncoder sectionEncoder) - { - final String mimeType = serverMessage.getMessageHeader().getMimeType(); - byte[] data = new byte[(int) serverMessage.getSize()]; - serverMessage.getContent(ByteBuffer.wrap(data), 0); - byte[] uncompressed; - - if(Symbol.valueOf(GZIPUtils.GZIP_CONTENT_ENCODING).equals(metaData.getPropertiesSection().getContentEncoding()) - && (uncompressed = GZIPUtils.uncompressBufferToArray(ByteBuffer.wrap(data)))!=null) - { - data = uncompressed; - metaData.getPropertiesSection().setContentEncoding(null); - } - - - Section bodySection = convertMessageBody(mimeType, data); - - final ByteBuffer allData = encodeConvertedMessage(metaData, bodySection, sectionEncoder); - - return new StoredMessage() - { - @Override - public MessageMetaData_1_0 getMetaData() - { - return metaData; - } - - @Override - public long getMessageNumber() - { - return serverMessage.getMessageNumber(); - } - - @Override - public int getContent(int offsetInMessage, ByteBuffer dst) - { - ByteBuffer buf = allData.duplicate(); - buf.position(offsetInMessage); - buf = buf.slice(); - int size; - if(dst.remaining() -{ - - static final AMQPDescribedTypeRegistry TYPE_REGISTRY = AMQPDescribedTypeRegistry.newInstance(); - static - { - TYPE_REGISTRY.registerTransportLayer(); - TYPE_REGISTRY.registerMessagingLayer(); - TYPE_REGISTRY.registerTransactionLayer(); - TYPE_REGISTRY.registerSecurityLayer(); - } - - @Override - public Class getInputClass() - { - return Message_1_0.class; - } - - @Override - public Class getOutputClass() - { - return InternalMessage.class; - } - - @Override - public InternalMessage convert(Message_1_0 serverMessage, VirtualHostImpl vhost) - { - Object bodyObject = MessageConverter_from_1_0.convertBodyToObject(serverMessage); - - return InternalMessage.convert(serverMessage.getMessageNumber(), serverMessage.isPersistent(), serverMessage.getMessageHeader(), bodyObject); - } - - @Override - public String getType() - { - return "v1-0 to Internal"; - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaDataType_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaDataType_1_0.java deleted file mode 100644 index 8f8a868365..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaDataType_1_0.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.protocol.v1_0; - -import java.nio.ByteBuffer; - -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.plugin.MessageMetaDataType; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.store.StoredMessage; - -@PluggableService -public class MessageMetaDataType_1_0 implements MessageMetaDataType -{ - - public static final int TYPE = 2; - public static final String V1_0_0 = "v1_0_0"; - - @Override - public int ordinal() - { - return TYPE; - } - - @Override - public MessageMetaData_1_0 createMetaData(ByteBuffer buf) - { - return MessageMetaData_1_0.FACTORY.createMetaData(buf); - } - - @Override - public ServerMessage createMessage(StoredMessage msg) - { - return new Message_1_0(msg); - } - - public int hashCode() - { - return ordinal(); - } - - public boolean equals(Object o) - { - return o != null && o.getClass() == getClass(); - } - - @Override - public String getType() - { - return V1_0_0; - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaData_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaData_1_0.java deleted file mode 100755 index d31909f642..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaData_1_0.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.protocol.v1_0; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.amqp_1_0.codec.ValueHandler; -import org.apache.qpid.amqp_1_0.messaging.SectionDecoder; -import org.apache.qpid.amqp_1_0.messaging.SectionEncoder; -import org.apache.qpid.amqp_1_0.type.AmqpErrorException; -import org.apache.qpid.amqp_1_0.type.Section; -import org.apache.qpid.amqp_1_0.type.Symbol; -import org.apache.qpid.amqp_1_0.type.codec.AMQPDescribedTypeRegistry; -import org.apache.qpid.amqp_1_0.type.messaging.AmqpSequence; -import org.apache.qpid.amqp_1_0.type.messaging.AmqpValue; -import org.apache.qpid.amqp_1_0.type.messaging.ApplicationProperties; -import org.apache.qpid.amqp_1_0.type.messaging.Data; -import org.apache.qpid.amqp_1_0.type.messaging.DeliveryAnnotations; -import org.apache.qpid.amqp_1_0.type.messaging.Footer; -import org.apache.qpid.amqp_1_0.type.messaging.Header; -import org.apache.qpid.amqp_1_0.type.messaging.MessageAnnotations; -import org.apache.qpid.amqp_1_0.type.messaging.Properties; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.plugin.MessageMetaDataType; -import org.apache.qpid.server.store.StorableMessageMetaData; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; - -public class MessageMetaData_1_0 implements StorableMessageMetaData -{ - private static final Logger _logger = LoggerFactory.getLogger(MessageMetaData_1_0.class); - // TODO move to somewhere more useful - public static final Symbol JMS_TYPE = Symbol.valueOf("x-opt-jms-type"); - public static final MessageMetaDataType.Factory FACTORY = new MetaDataFactory(); - private static final MessageMetaDataType_1_0 TYPE = new MessageMetaDataType_1_0(); - - - private Header _header; - private Properties _properties; - private Map _deliveryAnnotations; - private Map _messageAnnotations; - private Map _appProperties; - private Map _footer; - - private List _encodedSections = new ArrayList(3); - - private volatile ByteBuffer _encoded; - private MessageHeader_1_0 _messageHeader; - - - public MessageMetaData_1_0(List
sections, SectionEncoder encoder) - { - this(sections, encodeSections(sections, encoder)); - } - - public Properties getPropertiesSection() - { - return _properties; - } - - - public Header getHeaderSection() - { - return _header; - } - - private static ArrayList encodeSections(final List
sections, final SectionEncoder encoder) - { - ArrayList encodedSections = new ArrayList(sections.size()); - for(Section section : sections) - { - encoder.encodeObject(section); - encodedSections.add(encoder.getEncoding().asByteBuffer()); - encoder.reset(); - } - return encodedSections; - } - - public MessageMetaData_1_0(ByteBuffer[] fragments, SectionDecoder decoder) - { - this(fragments, decoder, new ArrayList(3)); - } - - public MessageMetaData_1_0(ByteBuffer[] fragments, SectionDecoder decoder, List immutableSections) - { - this(constructSections(fragments, decoder,immutableSections), immutableSections); - } - - private MessageMetaData_1_0(List
sections, List encodedSections) - { - _encodedSections = encodedSections; - - Iterator
sectIter = sections.iterator(); - - Section section = sectIter.hasNext() ? sectIter.next() : null; - if(section instanceof Header) - { - _header = (Header) section; - section = sectIter.hasNext() ? sectIter.next() : null; - } - - if(section instanceof DeliveryAnnotations) - { - _deliveryAnnotations = ((DeliveryAnnotations) section).getValue(); - section = sectIter.hasNext() ? sectIter.next() : null; - } - - if(section instanceof MessageAnnotations) - { - _messageAnnotations = ((MessageAnnotations) section).getValue(); - section = sectIter.hasNext() ? sectIter.next() : null; - } - - if(section instanceof Properties) - { - _properties = (Properties) section; - section = sectIter.hasNext() ? sectIter.next() : null; - } - - if(section instanceof ApplicationProperties) - { - _appProperties = ((ApplicationProperties) section).getValue(); - section = sectIter.hasNext() ? sectIter.next() : null; - } - - if(section instanceof Footer) - { - _footer = ((Footer) section).getValue(); - section = sectIter.hasNext() ? sectIter.next() : null; - } - - _messageHeader = new MessageHeader_1_0(); - - } - - private static List
constructSections(final ByteBuffer[] fragments, final SectionDecoder decoder, List encodedSections) - { - List
sections = new ArrayList
(3); - - ByteBuffer src; - if(fragments.length == 1) - { - src = fragments[0].duplicate(); - } - else - { - int size = 0; - for(ByteBuffer buf : fragments) - { - size += buf.remaining(); - } - src = ByteBuffer.allocate(size); - for(ByteBuffer buf : fragments) - { - src.put(buf.duplicate()); - } - src.flip(); - - } - - try - { - int startBarePos = -1; - int lastPos = src.position(); - Section s = decoder.readSection(src); - - - - if(s instanceof Header) - { - sections.add(s); - lastPos = src.position(); - s = src.hasRemaining() ? decoder.readSection(src) : null; - } - - if(s instanceof DeliveryAnnotations) - { - sections.add(s); - lastPos = src.position(); - s = src.hasRemaining() ? decoder.readSection(src) : null; - } - - if(s instanceof MessageAnnotations) - { - sections.add(s); - lastPos = src.position(); - s = src.hasRemaining() ? decoder.readSection(src) : null; - } - - if(s instanceof Properties) - { - sections.add(s); - if(startBarePos == -1) - { - startBarePos = lastPos; - } - s = src.hasRemaining() ? decoder.readSection(src) : null; - } - - if(s instanceof ApplicationProperties) - { - sections.add(s); - if(startBarePos == -1) - { - startBarePos = lastPos; - } - s = src.hasRemaining() ? decoder.readSection(src) : null; - } - - if(s instanceof AmqpValue) - { - if(startBarePos == -1) - { - startBarePos = lastPos; - } - s = src.hasRemaining() ? decoder.readSection(src) : null; - } - else if(s instanceof Data) - { - if(startBarePos == -1) - { - startBarePos = lastPos; - } - do - { - s = src.hasRemaining() ? decoder.readSection(src) : null; - } while(s instanceof Data); - } - else if(s instanceof AmqpSequence) - { - if(startBarePos == -1) - { - startBarePos = lastPos; - } - do - { - s = src.hasRemaining() ? decoder.readSection(src) : null; - } - while(s instanceof AmqpSequence); - } - - if(s instanceof Footer) - { - sections.add(s); - } - - - int pos = 0; - for(ByteBuffer buf : fragments) - { -/* - if(pos < startBarePos) - { - if(pos + buf.remaining() > startBarePos) - { - ByteBuffer dup = buf.duplicate(); - dup.position(dup.position()+startBarePos-pos); - dup.slice(); - encodedSections.add(dup); - } - } - else -*/ - { - encodedSections.add(buf.duplicate()); - } - pos += buf.remaining(); - } - - return sections; - } - catch (AmqpErrorException e) - { - _logger.error("Decoding read section error", e); - throw new IllegalArgumentException(e); - } - } - - - public MessageMetaDataType getType() - { - return TYPE; - } - - - public int getStorableSize() - { - int size = 0; - - for(ByteBuffer bin : _encodedSections) - { - size += bin.limit(); - } - - return size; - } - - private ByteBuffer encodeAsBuffer() - { - ByteBuffer buf = ByteBuffer.allocate(getStorableSize()); - - for(ByteBuffer bin : _encodedSections) - { - buf.put(bin.duplicate()); - } - - return buf; - } - - public int writeToBuffer(ByteBuffer dest) - { - ByteBuffer buf = _encoded; - - if(buf == null) - { - buf = encodeAsBuffer(); - _encoded = buf; - } - - buf = buf.duplicate(); - - buf.position(0); - - if(dest.remaining() < buf.limit()) - { - buf.limit(dest.remaining()); - } - dest.put(buf); - return buf.limit(); - } - - public int getContentSize() - { - ByteBuffer buf = _encoded; - - if(buf == null) - { - buf = encodeAsBuffer(); - _encoded = buf; - } - return buf.remaining(); - } - - public boolean isPersistent() - { - return _header != null && Boolean.TRUE.equals(_header.getDurable()); - } - - public MessageHeader_1_0 getMessageHeader() - { - return _messageHeader; - } - - - - - private static class MetaDataFactory implements MessageMetaDataType.Factory - { - private final AMQPDescribedTypeRegistry _typeRegistry = AMQPDescribedTypeRegistry.newInstance(); - - private MetaDataFactory() - { - _typeRegistry.registerTransportLayer(); - _typeRegistry.registerMessagingLayer(); - _typeRegistry.registerTransactionLayer(); - _typeRegistry.registerSecurityLayer(); - } - - public MessageMetaData_1_0 createMetaData(ByteBuffer buf) - { - ValueHandler valueHandler = new ValueHandler(_typeRegistry); - - ArrayList
sections = new ArrayList
(3); - ArrayList encodedSections = new ArrayList(3); - - while(buf.hasRemaining()) - { - try - { - ByteBuffer encodedBuf = buf.duplicate(); - Object parse = valueHandler.parse(buf); - sections.add((Section) parse); - encodedBuf.limit(buf.position()); - encodedSections.add(encodedBuf); - - } - catch (AmqpErrorException e) - { - //TODO - throw new ConnectionScopedRuntimeException(e); - } - - } - - return new MessageMetaData_1_0(sections,encodedSections); - - } - } - - public class MessageHeader_1_0 implements AMQMessageHeader - { - - public String getCorrelationId() - { - if(_properties == null || _properties.getCorrelationId() == null) - { - return null; - } - else - { - return _properties.getCorrelationId().toString(); - } - } - - public long getExpiration() - { - return 0; //TODO - } - - public String getMessageId() - { - if(_properties == null || _properties.getMessageId() == null) - { - return null; - } - else - { - return _properties.getMessageId().toString(); - } - } - - public String getMimeType() - { - - if(_properties == null || _properties.getContentType() == null) - { - return null; - } - else - { - return _properties.getContentType().toString(); - } - } - - public String getEncoding() - { - return null; //TODO - } - - public byte getPriority() - { - if(_header == null || _header.getPriority() == null) - { - return 4; //javax.jms.Message.DEFAULT_PRIORITY; - } - else - { - return _header.getPriority().byteValue(); - } - } - - public long getTimestamp() - { - if(_properties == null || _properties.getCreationTime() == null) - { - return 0L; - } - else - { - return _properties.getCreationTime().getTime(); - } - - } - - public String getType() - { - String subject = getSubject(); - if(subject != null) - { - return subject; - } - - // Use legacy annotation if present and there was no subject - if(_messageAnnotations == null || _messageAnnotations.get(JMS_TYPE) == null) - { - return null; - } - else - { - return _messageAnnotations.get(JMS_TYPE).toString(); - } - } - - public String getReplyTo() - { - if(_properties == null || _properties.getReplyTo() == null) - { - return null; - } - else - { - return _properties.getReplyTo().toString(); - } - } - - public String getAppId() - { - //TODO - return null; - } - - public String getUserId() - { - // TODO - return null; - } - - public Object getHeader(final String name) - { - return _appProperties == null ? null : _appProperties.get(name); - } - - public boolean containsHeaders(final Set names) - { - if(_appProperties == null) - { - return false; - } - - for(String key : names) - { - if(!_appProperties.containsKey(key)) - { - return false; - } - } - return true; - } - - @Override - public Collection getHeaderNames() - { - if(_appProperties == null) - { - return Collections.emptySet(); - } - return Collections.unmodifiableCollection(_appProperties.keySet()); - } - - public boolean containsHeader(final String name) - { - return _appProperties != null && _appProperties.containsKey(name); - } - - public String getSubject() - { - return _properties == null ? null : _properties.getSubject(); - } - - public String getTo() - { - return _properties == null ? null : _properties.getTo(); - } - - public Map getHeadersAsMap() - { - return new HashMap(_appProperties); - } - } - -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageSourceDestination.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageSourceDestination.java deleted file mode 100644 index 16c2de9271..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageSourceDestination.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.protocol.v1_0; - -import org.apache.qpid.amqp_1_0.type.Outcome; -import org.apache.qpid.amqp_1_0.type.messaging.Accepted; -import org.apache.qpid.server.message.MessageSource; - -public class MessageSourceDestination implements SendingDestination -{ - private static final Accepted ACCEPTED = new Accepted(); - private static final Outcome[] OUTCOMES = new Outcome[] { ACCEPTED }; - - - private MessageSource _queue; - - public MessageSourceDestination(MessageSource queue) - { - _queue = queue; - } - - public Outcome[] getOutcomes() - { - return OUTCOMES; - } - - public int getCredit() - { - // TODO - fix - return 100; - } - - public MessageSource getQueue() - { - return _queue; - } - -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Message_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Message_1_0.java deleted file mode 100644 index 18f5ba9e2e..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Message_1_0.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.server.protocol.v1_0; - - -import java.lang.ref.SoftReference; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.List; - -import org.apache.qpid.server.message.AbstractServerMessageImpl; -import org.apache.qpid.server.store.StoredMessage; - -public class Message_1_0 extends AbstractServerMessageImpl -{ - - private volatile SoftReference> _fragmentsRef; - private long _arrivalTime; - private final long _size; - - - public Message_1_0(final StoredMessage storedMessage) - { - super(storedMessage, null); - final List fragments = restoreFragments(getStoredMessage()); - _fragmentsRef = new SoftReference<>(fragments); - _size = calculateSize(fragments); - } - - private long calculateSize(final List fragments) - { - - long size = 0l; - if(fragments != null) - { - for(ByteBuffer buf : fragments) - { - size += buf.remaining(); - } - } - return size; - } - - private static List restoreFragments(StoredMessage storedMessage) - { - ArrayList fragments = new ArrayList(); - final int FRAGMENT_SIZE = 2048; - int offset = 0; - ByteBuffer b; - do - { - - b = storedMessage.getContent(offset,FRAGMENT_SIZE); - if(b.hasRemaining()) - { - fragments.add(b); - offset+= b.remaining(); - } - } - while(b.hasRemaining()); - return fragments; - } - - public Message_1_0(final StoredMessage storedMessage, - final List fragments, - final Object connectionReference) - { - super(storedMessage, connectionReference); - _fragmentsRef = new SoftReference<>(fragments); - _size = calculateSize(fragments); - _arrivalTime = System.currentTimeMillis(); - } - - public String getInitialRoutingAddress() - { - Object routingKey = getMessageHeader().getHeader("routing-key"); - if(routingKey != null) - { - return routingKey.toString(); - } - else - { - return getMessageHeader().getTo(); - } - } - - private MessageMetaData_1_0 getMessageMetaData() - { - return getStoredMessage().getMetaData(); - } - - public MessageMetaData_1_0.MessageHeader_1_0 getMessageHeader() - { - return getMessageMetaData().getMessageHeader(); - } - - public long getSize() - { - return _size; - } - - public long getExpiration() - { - return getMessageHeader().getExpiration(); - } - - public long getArrivalTime() - { - return _arrivalTime; - } - - public List getFragments() - { - - List fragments = _fragmentsRef.get(); - if(fragments == null) - { - fragments = restoreFragments(getStoredMessage()); - _fragmentsRef = new SoftReference<>(fragments); - } - return fragments; - } - -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/NodeReceivingDestination.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/NodeReceivingDestination.java deleted file mode 100644 index 10058c1e0a..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/NodeReceivingDestination.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.server.protocol.v1_0; - -import org.apache.qpid.amqp_1_0.type.Outcome; -import org.apache.qpid.amqp_1_0.type.messaging.Accepted; -import org.apache.qpid.amqp_1_0.type.messaging.Rejected; -import org.apache.qpid.amqp_1_0.type.messaging.TerminusDurability; -import org.apache.qpid.amqp_1_0.type.messaging.TerminusExpiryPolicy; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.MessageDestination; -import org.apache.qpid.server.txn.ServerTransaction; - -public class NodeReceivingDestination implements ReceivingDestination -{ - private static final Accepted ACCEPTED = new Accepted(); - public static final Rejected REJECTED = new Rejected(); - private static final Outcome[] OUTCOMES = { ACCEPTED, REJECTED}; - - private MessageDestination _destination; - private TerminusDurability _durability; - private TerminusExpiryPolicy _expiryPolicy; - - public NodeReceivingDestination(MessageDestination destination, TerminusDurability durable, TerminusExpiryPolicy expiryPolicy) - { - _destination = destination; - _durability = durable; - _expiryPolicy = expiryPolicy; - } - - public Outcome[] getOutcomes() - { - return OUTCOMES; - } - - public Outcome send(final Message_1_0 message, ServerTransaction txn) - { - final InstanceProperties instanceProperties = - new InstanceProperties() - { - - @Override - public Object getProperty(final Property prop) - { - switch(prop) - { - case MANDATORY: - return false; - case REDELIVERED: - return false; - case PERSISTENT: - return message.isPersistent(); - case IMMEDIATE: - return false; - case EXPIRATION: - return message.getExpiration(); - } - return null; - }}; - - String routingAddress; - MessageMetaData_1_0.MessageHeader_1_0 messageHeader = message.getMessageHeader(); - routingAddress = messageHeader.getSubject(); - if(routingAddress == null) - { - if (messageHeader.getHeader("routing-key") instanceof String) - { - routingAddress = (String) messageHeader.getHeader("routing-key"); - } - else if (messageHeader.getHeader("routing_key") instanceof String) - { - routingAddress = (String) messageHeader.getHeader("routing_key"); - } - else if (messageHeader.getTo() != null - && messageHeader.getTo().startsWith(_destination.getName() + "/")) - { - routingAddress = messageHeader.getTo().substring(1+_destination.getName().length()); - } - else - { - routingAddress = ""; - } - } - - int enqueues = _destination.send(message, routingAddress, instanceProperties, txn, null); - - - return enqueues == 0 ? REJECTED : ACCEPTED; - } - - TerminusDurability getDurability() - { - return _durability; - } - - TerminusExpiryPolicy getExpiryPolicy() - { - return _expiryPolicy; - } - - public int getCredit() - { - // TODO - fix - return 20000; - } - - public MessageDestination getDestination() - { - return _destination; - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ProtocolEngineCreator_1_0_0_SASL.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ProtocolEngineCreator_1_0_0_SASL.java deleted file mode 100644 index e72dc17b57..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ProtocolEngineCreator_1_0_0_SASL.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.protocol.v1_0; - -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Protocol; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.plugin.ProtocolEngineCreator; -import org.apache.qpid.transport.network.NetworkConnection; - -@PluggableService -public class ProtocolEngineCreator_1_0_0_SASL implements ProtocolEngineCreator -{ - private static final byte[] AMQP_SASL_1_0_0_HEADER = - new byte[] { (byte) 'A', - (byte) 'M', - (byte) 'Q', - (byte) 'P', - (byte) 3, - (byte) 1, - (byte) 0, - (byte) 0 - }; - - public ProtocolEngineCreator_1_0_0_SASL() - { - } - - public Protocol getVersion() - { - return Protocol.AMQP_1_0; - } - - - public byte[] getHeaderIdentifier() - { - return AMQP_SASL_1_0_0_HEADER; - } - - public ServerProtocolEngine newProtocolEngine(Broker broker, - NetworkConnection network, - AmqpPort port, - Transport transport, - long id) - { - return new ProtocolEngine_1_0_0_SASL(network, broker, id, port, transport); - } - - private static ProtocolEngineCreator INSTANCE = new ProtocolEngineCreator_1_0_0_SASL(); - - public static ProtocolEngineCreator getInstance() - { - return INSTANCE; - } - - @Override - public String getType() - { - return getVersion().toString(); - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ProtocolEngine_1_0_0_SASL.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ProtocolEngine_1_0_0_SASL.java deleted file mode 100644 index 013126cfe0..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ProtocolEngine_1_0_0_SASL.java +++ /dev/null @@ -1,631 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.v1_0; - -import java.io.PrintWriter; -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.security.Principal; -import java.security.PrivilegedAction; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -import javax.security.auth.Subject; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.amqp_1_0.codec.FrameWriter; -import org.apache.qpid.amqp_1_0.codec.ProtocolHandler; -import org.apache.qpid.amqp_1_0.framing.AMQFrame; -import org.apache.qpid.amqp_1_0.framing.OversizeFrameException; -import org.apache.qpid.amqp_1_0.framing.SASLFrameHandler; -import org.apache.qpid.amqp_1_0.transport.ConnectionEndpoint; -import org.apache.qpid.amqp_1_0.transport.Container; -import org.apache.qpid.amqp_1_0.transport.FrameOutputHandler; -import org.apache.qpid.amqp_1_0.transport.SaslServerProvider; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.FrameBody; -import org.apache.qpid.amqp_1_0.type.Symbol; -import org.apache.qpid.common.QpidProperties; -import org.apache.qpid.common.ServerPropertyNames; -import org.apache.qpid.server.protocol.ServerProtocolEngine; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Consumer; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.security.SubjectCreator; -import org.apache.qpid.server.security.auth.UsernamePrincipal; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.transport.ByteBufferSender; -import org.apache.qpid.transport.network.NetworkConnection; - -public class ProtocolEngine_1_0_0_SASL implements ServerProtocolEngine, FrameOutputHandler -{ - - private final AmqpPort _port; - private final Transport _transport; - private long _readBytes; - private long _writtenBytes; - - private volatile long _lastReadTime; - private volatile long _lastWriteTime; - private final Broker _broker; - private long _createTime = System.currentTimeMillis(); - private ConnectionEndpoint _endpoint; - private long _connectionId; - private final AtomicBoolean _stateChanged = new AtomicBoolean(); - private final AtomicReference> _workListener = new AtomicReference<>(); - - - private static final ByteBuffer HEADER = - ByteBuffer.wrap(new byte[] - { - (byte)'A', - (byte)'M', - (byte)'Q', - (byte)'P', - (byte) 3, - (byte) 1, - (byte) 0, - (byte) 0 - }); - - private static final ByteBuffer PROTOCOL_HEADER = - ByteBuffer.wrap(new byte[] - { - (byte)'A', - (byte)'M', - (byte)'Q', - (byte)'P', - (byte) 0, - (byte) 1, - (byte) 0, - (byte) 0 - }); - - - private FrameWriter _frameWriter; - private ProtocolHandler _frameHandler; - private ByteBuffer _buf = ByteBuffer.allocate(1024 * 1024); - private Object _sendLock = new Object(); - private byte _major; - private byte _minor; - private byte _revision; - private PrintWriter _out; - private NetworkConnection _network; - private ByteBufferSender _sender; - private Connection_1_0 _connection; - private volatile boolean _transportBlockedForWriting; - - - static enum State { - A, - M, - Q, - P, - PROTOCOL, - MAJOR, - MINOR, - REVISION, - FRAME - } - - private State _state = State.A; - - private final AtomicReference _messageAssignmentSuspended = new AtomicReference<>(); - - - - - public ProtocolEngine_1_0_0_SASL(final NetworkConnection networkDriver, final Broker broker, - long id, AmqpPort port, Transport transport) - { - _connectionId = id; - _broker = broker; - _port = port; - _transport = transport; - if(networkDriver != null) - { - setNetworkConnection(networkDriver, networkDriver.getSender()); - } - } - - - @Override - public boolean isMessageAssignmentSuspended() - { - Thread lock = _messageAssignmentSuspended.get(); - return lock != null && _messageAssignmentSuspended.get() != Thread.currentThread(); - } - - @Override - public void setMessageAssignmentSuspended(final boolean messageAssignmentSuspended) - { - _messageAssignmentSuspended.set(messageAssignmentSuspended ? Thread.currentThread() : null); - - for(AMQSessionModel session : _connection.getSessionModels()) - { - for(Consumer consumer : session.getConsumers()) - { - ConsumerImpl consumerImpl = (ConsumerImpl) consumer; - if (!messageAssignmentSuspended) - { - consumerImpl.getTarget().notifyCurrentState(); - } - else - { - // ensure that by the time the method returns, no consumer can be in the process of - // delivering a message. - consumerImpl.getSendLock(); - consumerImpl.releaseSendLock(); - } - } - } - } - - - public SocketAddress getRemoteAddress() - { - return _network.getRemoteAddress(); - } - - public SocketAddress getLocalAddress() - { - return _network.getLocalAddress(); - } - - public long getReadBytes() - { - return _readBytes; - } - - public long getWrittenBytes() - { - return _writtenBytes; - } - - public void writerIdle() - { - //Todo - } - - public void readerIdle() - { - //Todo - } - - @Override - public void encryptedTransport() - { - } - - public void setNetworkConnection(final NetworkConnection network, final ByteBufferSender sender) - { - _network = network; - _sender = sender; - - Container container = new Container(_broker.getId().toString()); - - SubjectCreator subjectCreator = _port.getAuthenticationProvider().getSubjectCreator(_transport.isSecure()); - _endpoint = new ConnectionEndpoint(container, asSaslServerProvider(subjectCreator)); - _endpoint.setLogger(new ConnectionEndpoint.FrameReceiptLogger() - { - @Override - public boolean isEnabled() - { - return FRAME_LOGGER.isDebugEnabled(); - } - - @Override - public void received(final SocketAddress remoteAddress, final short channel, final Object frame) - { - FRAME_LOGGER.debug("RECV[" + remoteAddress + "|" + channel + "] : " + frame); - } - }); - Map serverProperties = new LinkedHashMap(); - serverProperties.put(Symbol.valueOf(ServerPropertyNames.PRODUCT), QpidProperties.getProductName()); - serverProperties.put(Symbol.valueOf(ServerPropertyNames.VERSION), QpidProperties.getReleaseVersion()); - serverProperties.put(Symbol.valueOf(ServerPropertyNames.QPID_BUILD), QpidProperties.getBuildVersion()); - serverProperties.put(Symbol.valueOf(ServerPropertyNames.QPID_INSTANCE_NAME), _broker.getName()); - - _endpoint.setProperties(serverProperties); - - _endpoint.setRemoteAddress(getRemoteAddress()); - _connection = new Connection_1_0(_broker, _endpoint, _connectionId, _port, _transport, subjectCreator, this); - - _endpoint.setConnectionEventListener(_connection); - _endpoint.setFrameOutputHandler(this); - _endpoint.setSaslFrameOutput(this); - - _endpoint.setOnSaslComplete(new Runnable() - { - public void run() - { - if (_endpoint.isAuthenticated()) - { - _sender.send(PROTOCOL_HEADER.duplicate()); - _sender.flush(); - } - else - { - _network.close(); - } - } - }); - _frameWriter = new FrameWriter(_endpoint.getDescribedTypeRegistry()); - _frameHandler = new SASLFrameHandler(_endpoint); - - _sender.send(HEADER.duplicate()); - _sender.flush(); - - List mechanisms = subjectCreator.getMechanisms(); - _endpoint.initiateSASL(mechanisms.toArray(new String[mechanisms.size()])); - - - } - - private SaslServerProvider asSaslServerProvider(final SubjectCreator subjectCreator) - { - return new SaslServerProvider() - { - @Override - public SaslServer getSaslServer(String mechanism, String fqdn) throws SaslException - { - return subjectCreator.createSaslServer(mechanism, fqdn, _network.getPeerPrincipal()); - } - - @Override - public Principal getAuthenticatedPrincipal(SaslServer server) - { - return new UsernamePrincipal(server.getAuthorizationID()); - } - }; - } - - public String getAddress() - { - return getRemoteAddress().toString(); - } - - public boolean isDurable() - { - return false; - } - - private final Logger RAW_LOGGER = LoggerFactory.getLogger("RAW"); - - - public synchronized void received(final ByteBuffer msg) - { - try - { - _lastReadTime = System.currentTimeMillis(); - if(RAW_LOGGER.isDebugEnabled()) - { - ByteBuffer dup = msg.duplicate(); - byte[] data = new byte[dup.remaining()]; - dup.get(data); - Binary bin = new Binary(data); - RAW_LOGGER.debug("RECV[" + getRemoteAddress() + "] : " + bin.toString()); - } - _readBytes += msg.remaining(); - switch(_state) - { - case A: - if (msg.hasRemaining()) - { - msg.get(); - } - else - { - break; - } - case M: - if (msg.hasRemaining()) - { - msg.get(); - } - else - { - _state = State.M; - break; - } - - case Q: - if (msg.hasRemaining()) - { - msg.get(); - } - else - { - _state = State.Q; - break; - } - case P: - if (msg.hasRemaining()) - { - msg.get(); - } - else - { - _state = State.P; - break; - } - case PROTOCOL: - if (msg.hasRemaining()) - { - msg.get(); - } - else - { - _state = State.PROTOCOL; - break; - } - case MAJOR: - if (msg.hasRemaining()) - { - _major = msg.get(); - } - else - { - _state = State.MAJOR; - break; - } - case MINOR: - if (msg.hasRemaining()) - { - _minor = msg.get(); - } - else - { - _state = State.MINOR; - break; - } - case REVISION: - if (msg.hasRemaining()) - { - _revision = msg.get(); - - _state = State.FRAME; - } - else - { - _state = State.REVISION; - break; - } - case FRAME: - if (msg.hasRemaining()) - { - Subject.doAs(_connection.getSubject(), new PrivilegedAction() - { - @Override - public Void run() - { - _frameHandler = _frameHandler.parse(msg); - return null; - } - }); - - } - } - } - catch(RuntimeException e) - { - exception(e); - } - } - - public void exception(Throwable throwable) - { - // noop - exception method is not used by new i/o layer - } - - public void closed() - { - try - { - // todo - try - { - _endpoint.inputClosed(); - } - finally - { - if (_endpoint != null && _endpoint.getConnectionEventListener() != null) - { - ((Connection_1_0) _endpoint.getConnectionEventListener()).closed(); - } - } - } - catch(RuntimeException e) - { - exception(e); - } - } - - public long getCreateTime() - { - return _createTime; - } - - - public boolean canSend() - { - return true; - } - - public void send(final AMQFrame amqFrame) - { - send(amqFrame, null); - } - - private static final Logger FRAME_LOGGER = LoggerFactory.getLogger("FRM"); - - - public void send(final AMQFrame amqFrame, ByteBuffer buf) - { - - synchronized (_sendLock) - { - _lastWriteTime = System.currentTimeMillis(); - if (FRAME_LOGGER.isDebugEnabled()) - { - FRAME_LOGGER.debug("SEND[" - + getRemoteAddress() - + "|" - + amqFrame.getChannel() - + "] : " - + amqFrame.getFrameBody()); - } - - _frameWriter.setValue(amqFrame); - - ByteBuffer dup = ByteBuffer.allocate(_endpoint.getMaxFrameSize()); - - int size = _frameWriter.writeToBuffer(dup); - if (size > _endpoint.getMaxFrameSize()) - { - throw new OversizeFrameException(amqFrame, size); - } - - dup.flip(); - _writtenBytes += dup.limit(); - - if (RAW_LOGGER.isDebugEnabled()) - { - ByteBuffer dup2 = dup.duplicate(); - byte[] data = new byte[dup2.remaining()]; - dup2.get(data); - Binary bin = new Binary(data); - RAW_LOGGER.debug("SEND[" + getRemoteAddress() + "] : " + bin.toString()); - } - - _sender.send(dup); - _sender.flush(); - - - } - } - - public void send(short channel, FrameBody body) - { - AMQFrame frame = AMQFrame.createAMQFrame(channel, body); - send(frame); - - } - - - - public void close() - { - _sender.close(); - } - - public void setLogOutput(final PrintWriter out) - { - _out = out; - } - - public long getConnectionId() - { - return _connectionId; - } - - @Override - public Subject getSubject() - { - return _connection.getSubject(); - } - - public long getLastReadTime() - { - return _lastReadTime; - } - - public long getLastWriteTime() - { - return _lastWriteTime; - } - - @Override - public boolean isTransportBlockedForWriting() - { - return _transportBlockedForWriting; - } - @Override - public void setTransportBlockedForWriting(final boolean blocked) - { - _transportBlockedForWriting = blocked; - _connection.transportStateChanged(); - - } - - public void flushBatched() - { - _sender.flush(); - } - - @Override - public void processPending() - { - _connection.processPending(); - - } - - @Override - public boolean hasWork() - { - return _stateChanged.get(); - } - - @Override - public void notifyWork() - { - _stateChanged.set(true); - - final Action listener = _workListener.get(); - if(listener != null) - { - listener.performAction(this); - } - } - - @Override - public void clearWork() - { - _stateChanged.set(false); - } - - @Override - public void setWorkListener(final Action listener) - { - _workListener.set(listener); - } - -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/QueueDestination.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/QueueDestination.java deleted file mode 100644 index e8e31dcd15..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/QueueDestination.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.protocol.v1_0; - -import org.apache.qpid.amqp_1_0.type.Outcome; -import org.apache.qpid.amqp_1_0.type.messaging.Accepted; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.store.MessageEnqueueRecord; -import org.apache.qpid.server.txn.ServerTransaction; - -public class QueueDestination extends MessageSourceDestination implements SendingDestination, ReceivingDestination -{ - private static final Accepted ACCEPTED = new Accepted(); - private static final Outcome[] OUTCOMES = new Outcome[] { ACCEPTED }; - - - public QueueDestination(AMQQueue queue) - { - super(queue); - } - - public Outcome[] getOutcomes() - { - return OUTCOMES; - } - - public Outcome send(final Message_1_0 message, ServerTransaction txn) - { - - txn.enqueue(getQueue(),message, new ServerTransaction.EnqueueAction() - { - MessageReference _reference = message.newReference(); - - - public void postCommit(MessageEnqueueRecord... records) - { - try - { - getQueue().enqueue(message, null, records[0]); - } - finally - { - _reference.release(); - } - } - - public void onRollback() - { - _reference.release(); - } - }); - - - return ACCEPTED; - } - - public int getCredit() - { - // TODO - fix - return 100; - } - - public AMQQueue getQueue() - { - return (AMQQueue) super.getQueue(); - } - -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingDestination.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingDestination.java deleted file mode 100644 index 4ae0596e25..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingDestination.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.protocol.v1_0; - -import org.apache.qpid.amqp_1_0.type.Outcome; - -import org.apache.qpid.server.txn.ServerTransaction; - -public interface ReceivingDestination extends Destination -{ - - Outcome[] getOutcomes(); - - Outcome send(Message_1_0 message, ServerTransaction txn); - - int getCredit(); -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingLinkAttachment.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingLinkAttachment.java deleted file mode 100644 index 46b9682c74..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingLinkAttachment.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.protocol.v1_0; - -import org.apache.qpid.amqp_1_0.transport.DeliveryStateHandler; -import org.apache.qpid.amqp_1_0.transport.ReceivingLinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.SendingLinkEndpoint; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.DeliveryState; -import org.apache.qpid.amqp_1_0.type.Source; -import org.apache.qpid.amqp_1_0.type.Target; - -public class ReceivingLinkAttachment -{ - private final Session_1_0 _session; - private final ReceivingLinkEndpoint _endpoint; - - public ReceivingLinkAttachment(final Session_1_0 session, final ReceivingLinkEndpoint endpoint) - { - _session = session; - _endpoint = endpoint; - } - - public Session_1_0 getSession() - { - return _session; - } - - public ReceivingLinkEndpoint getEndpoint() - { - return _endpoint; - } - - public Source getSource() - { - return getEndpoint().getSource(); - } - - public void setDeliveryStateHandler(final DeliveryStateHandler handler) - { - getEndpoint().setDeliveryStateHandler(handler); - } - - public void updateDisposition(final Binary deliveryTag, final DeliveryState state, final boolean settled) - { - getEndpoint().updateDisposition(deliveryTag, state, settled); - } - - public Target getTarget() - { - return getEndpoint().getTarget(); - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingLink_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingLink_1_0.java deleted file mode 100644 index 5deec2bb35..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingLink_1_0.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.server.protocol.v1_0; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.qpid.amqp_1_0.messaging.SectionDecoderImpl; -import org.apache.qpid.amqp_1_0.transport.DeliveryStateHandler; -import org.apache.qpid.amqp_1_0.transport.LinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.ReceivingLinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.ReceivingLinkListener; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.DeliveryState; -import org.apache.qpid.amqp_1_0.type.Outcome; -import org.apache.qpid.amqp_1_0.type.UnsignedInteger; -import org.apache.qpid.amqp_1_0.type.messaging.Target; -import org.apache.qpid.amqp_1_0.type.messaging.TerminusDurability; -import org.apache.qpid.amqp_1_0.type.transaction.TransactionalState; -import org.apache.qpid.amqp_1_0.type.transport.Detach; -import org.apache.qpid.amqp_1_0.type.transport.ReceiverSettleMode; -import org.apache.qpid.amqp_1_0.type.transport.Transfer; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.store.MessageHandle; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.txn.AutoCommitTransaction; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; - -public class ReceivingLink_1_0 implements ReceivingLinkListener, Link_1_0, DeliveryStateHandler -{ - private VirtualHostImpl _vhost; - - private ReceivingDestination _destination; - private SectionDecoderImpl _sectionDecoder; - private volatile ReceivingLinkAttachment _attachment; - - - private ArrayList _incompleteMessage; - private TerminusDurability _durability; - - private Map _unsettledMap = Collections.synchronizedMap(new HashMap()); - private boolean _resumedMessage; - private Binary _messageDeliveryTag; - private ReceiverSettleMode _receivingSettlementMode; - - - public ReceivingLink_1_0(ReceivingLinkAttachment receivingLinkAttachment, VirtualHostImpl vhost, - ReceivingDestination destination) - { - _vhost = vhost; - _destination = destination; - _attachment = receivingLinkAttachment; - _receivingSettlementMode = receivingLinkAttachment.getEndpoint().getReceivingSettlementMode(); - - receivingLinkAttachment.setDeliveryStateHandler(this); - - _durability = ((Target)receivingLinkAttachment.getTarget()).getDurable(); - - _sectionDecoder = new SectionDecoderImpl(receivingLinkAttachment.getEndpoint().getSession().getConnection().getDescribedTypeRegistry()); - - - } - - public void messageTransfer(Transfer xfr) - { - // TODO - cope with fragmented messages - - List fragments = null; - - - - if(Boolean.TRUE.equals(xfr.getMore()) && _incompleteMessage == null) - { - _incompleteMessage = new ArrayList(); - _incompleteMessage.add(xfr); - _resumedMessage = Boolean.TRUE.equals(xfr.getResume()); - _messageDeliveryTag = xfr.getDeliveryTag(); - return; - } - else if(_incompleteMessage != null) - { - _incompleteMessage.add(xfr); - - if(Boolean.TRUE.equals(xfr.getMore())) - { - return; - } - - fragments = new ArrayList(_incompleteMessage.size()); - for(Transfer t : _incompleteMessage) - { - fragments.add(t.getPayload()); - } - _incompleteMessage=null; - - } - else - { - _resumedMessage = Boolean.TRUE.equals(xfr.getResume()); - _messageDeliveryTag = xfr.getDeliveryTag(); - fragments = Collections.singletonList(xfr.getPayload()); - } - - if(_resumedMessage) - { - if(_unsettledMap.containsKey(_messageDeliveryTag)) - { - Outcome outcome = _unsettledMap.get(_messageDeliveryTag); - boolean settled = ReceiverSettleMode.FIRST.equals(getReceivingSettlementMode()); - getEndpoint().updateDisposition(_messageDeliveryTag, (DeliveryState) outcome, settled); - if(settled) - { - _unsettledMap.remove(_messageDeliveryTag); - } - } - else - { - System.err.println("UNEXPECTED!!"); - System.err.println("Delivery Tag: " + _messageDeliveryTag); - System.err.println("_unsettledMap: " + _unsettledMap); - - } - } - else - { - MessageMetaData_1_0 mmd = null; - List immutableSections = new ArrayList(3); - mmd = new MessageMetaData_1_0(fragments.toArray(new ByteBuffer[fragments.size()]), - _sectionDecoder, - immutableSections); - - MessageHandle handle = _vhost.getMessageStore().addMessage(mmd); - - boolean skipping = true; - int offset = 0; - - for(ByteBuffer bareMessageBuf : immutableSections) - { - handle.addContent(bareMessageBuf.duplicate()); - offset += bareMessageBuf.remaining(); - } - final StoredMessage storedMessage = handle.allContentAdded(); - Message_1_0 message = new Message_1_0(storedMessage, fragments, getSession().getConnection().getReference()); - MessageReference reference = message.newReference(); - - Binary transactionId = null; - org.apache.qpid.amqp_1_0.type.DeliveryState xfrState = xfr.getState(); - if(xfrState != null) - { - if(xfrState instanceof TransactionalState) - { - transactionId = ((TransactionalState)xfrState).getTxnId(); - } - } - - ServerTransaction transaction = null; - if(transactionId != null) - { - transaction = getSession().getTransaction(transactionId); - } - else - { - Session_1_0 session = getSession(); - transaction = session != null ? session.getTransaction(null) : new AutoCommitTransaction(_vhost.getMessageStore()); - } - - Outcome outcome = _destination.send(message, transaction); - - DeliveryState resultantState; - - if(transactionId == null) - { - resultantState = (DeliveryState) outcome; - } - else - { - TransactionalState transactionalState = new TransactionalState(); - transactionalState.setOutcome(outcome); - transactionalState.setTxnId(transactionId); - resultantState = transactionalState; - - } - - - boolean settled = transaction instanceof AutoCommitTransaction && ReceiverSettleMode.FIRST.equals(getReceivingSettlementMode()); - - final Binary deliveryTag = xfr.getDeliveryTag(); - - if(!settled) - { - _unsettledMap.put(deliveryTag, outcome); - } - - getEndpoint().updateDisposition(deliveryTag, resultantState, settled); - - getSession().getConnectionModel().registerMessageReceived(message.getSize(), message.getArrivalTime()); - - if(!(transaction instanceof AutoCommitTransaction)) - { - ServerTransaction.Action a; - transaction.addPostTransactionAction(new ServerTransaction.Action() - { - public void postCommit() - { - getEndpoint().updateDisposition(deliveryTag, null, true); - } - - public void onRollback() - { - getEndpoint().updateDisposition(deliveryTag, null, true); - } - }); - } - - reference.release(); - } - } - - private ReceiverSettleMode getReceivingSettlementMode() - { - return _receivingSettlementMode; - } - - public void remoteDetached(LinkEndpoint endpoint, Detach detach) - { - //TODO - // if not durable or close - if(!TerminusDurability.UNSETTLED_STATE.equals(_durability) || - (detach != null && Boolean.TRUE.equals(detach.getClosed()))) - { - endpoint.close(); - } - else if(detach == null || detach.getError() != null) - { - _attachment = null; - } - } - - public void start() - { - getEndpoint().setLinkCredit(UnsignedInteger.valueOf(_destination.getCredit())); - getEndpoint().setCreditWindow(); - } - - public ReceivingLinkEndpoint getEndpoint() - { - return _attachment.getEndpoint(); - } - - - public Session_1_0 getSession() - { - ReceivingLinkAttachment attachment = _attachment; - return attachment == null ? null : attachment.getSession(); - } - - public void handle(Binary deliveryTag, DeliveryState state, Boolean settled) - { - if(Boolean.TRUE.equals(settled)) - { - _unsettledMap.remove(deliveryTag); - } - } - - public void setLinkAttachment(ReceivingLinkAttachment linkAttachment) - { - _attachment = linkAttachment; - _receivingSettlementMode = linkAttachment.getEndpoint().getReceivingSettlementMode(); - ReceivingLinkEndpoint endpoint = linkAttachment.getEndpoint(); - Map initialUnsettledMap = endpoint.getInitialUnsettledMap(); - - Map unsettledCopy = new HashMap(_unsettledMap); - for(Map.Entry entry : unsettledCopy.entrySet()) - { - Binary deliveryTag = entry.getKey(); - if(!initialUnsettledMap.containsKey(deliveryTag)) - { - _unsettledMap.remove(deliveryTag); - } - } - - } - - public Map getUnsettledOutcomeMap() - { - return _unsettledMap; - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingDestination.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingDestination.java deleted file mode 100644 index 6d601c9dda..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingDestination.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.protocol.v1_0; - - -public interface SendingDestination extends Destination -{ - -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLinkAttachment.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLinkAttachment.java deleted file mode 100644 index 09a2ddea3a..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLinkAttachment.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.protocol.v1_0; - -import org.apache.qpid.amqp_1_0.transport.DeliveryStateHandler; -import org.apache.qpid.amqp_1_0.transport.SendingLinkEndpoint; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.DeliveryState; -import org.apache.qpid.amqp_1_0.type.Source; - -public class SendingLinkAttachment -{ - private final Session_1_0 _session; - private final SendingLinkEndpoint _endpoint; - - public SendingLinkAttachment(final Session_1_0 session, final SendingLinkEndpoint endpoint) - { - _session = session; - _endpoint = endpoint; - } - - public Session_1_0 getSession() - { - return _session; - } - - public SendingLinkEndpoint getEndpoint() - { - return _endpoint; - } - - public Source getSource() - { - return getEndpoint().getSource(); - } - - public void setDeliveryStateHandler(final DeliveryStateHandler handler) - { - getEndpoint().setDeliveryStateHandler(handler); - } - - public void updateDisposition(final Binary deliveryTag, final DeliveryState state, final boolean settled) - { - getEndpoint().updateDisposition(deliveryTag, state, settled); - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLink_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLink_1_0.java deleted file mode 100644 index ec57284a78..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLink_1_0.java +++ /dev/null @@ -1,719 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.v1_0; - -import java.security.AccessControlException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.amqp_1_0.transport.DeliveryStateHandler; -import org.apache.qpid.amqp_1_0.transport.LinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.SendingLinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.SendingLinkListener; -import org.apache.qpid.amqp_1_0.type.AmqpErrorException; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.DeliveryState; -import org.apache.qpid.amqp_1_0.type.Outcome; -import org.apache.qpid.amqp_1_0.type.Symbol; -import org.apache.qpid.amqp_1_0.type.UnsignedInteger; -import org.apache.qpid.amqp_1_0.type.messaging.Accepted; -import org.apache.qpid.amqp_1_0.type.messaging.ExactSubjectFilter; -import org.apache.qpid.amqp_1_0.type.messaging.Filter; -import org.apache.qpid.amqp_1_0.type.messaging.MatchingSubjectFilter; -import org.apache.qpid.amqp_1_0.type.messaging.Modified; -import org.apache.qpid.amqp_1_0.type.messaging.NoLocalFilter; -import org.apache.qpid.amqp_1_0.type.messaging.Released; -import org.apache.qpid.amqp_1_0.type.messaging.Source; -import org.apache.qpid.amqp_1_0.type.messaging.StdDistMode; -import org.apache.qpid.amqp_1_0.type.messaging.Target; -import org.apache.qpid.amqp_1_0.type.messaging.TerminusDurability; -import org.apache.qpid.amqp_1_0.type.transport.AmqpError; -import org.apache.qpid.amqp_1_0.type.transport.Detach; -import org.apache.qpid.amqp_1_0.type.transport.Error; -import org.apache.qpid.amqp_1_0.type.transport.Transfer; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.filter.SelectorParsingException; -import org.apache.qpid.filter.selector.ParseException; -import org.apache.qpid.server.binding.BindingImpl; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.exchange.ExchangeImpl; -import org.apache.qpid.server.filter.FilterManager; -import org.apache.qpid.server.filter.JMSSelectorFilter; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.server.message.MessageSource; -import org.apache.qpid.server.model.ExclusivityPolicy; -import org.apache.qpid.server.model.LifetimePolicy; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.txn.AutoCommitTransaction; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.server.virtualhost.QueueExistsException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; - -public class SendingLink_1_0 implements SendingLinkListener, Link_1_0, DeliveryStateHandler -{ - private static final Logger _logger = LoggerFactory.getLogger(SendingLink_1_0.class); - - private VirtualHostImpl _vhost; - private SendingDestination _destination; - - private ConsumerImpl _consumer; - private ConsumerTarget_1_0 _target; - - private boolean _draining; - private final Map _unsettledMap = - new HashMap(); - - private final ConcurrentMap _unsettledActionMap = - new ConcurrentHashMap(); - private volatile SendingLinkAttachment _linkAttachment; - private TerminusDurability _durability; - private List _resumeFullTransfers = new ArrayList(); - private List _resumeAcceptedTransfers = new ArrayList(); - private Runnable _closeAction; - private final MessageSource _queue; - - - public SendingLink_1_0(final SendingLinkAttachment linkAttachment, - final VirtualHostImpl vhost, - final SendingDestination destination) - throws AmqpErrorException - { - _vhost = vhost; - _destination = destination; - _linkAttachment = linkAttachment; - final Source source = (Source) linkAttachment.getSource(); - _durability = source.getDurable(); - linkAttachment.setDeliveryStateHandler(this); - QueueDestination qd = null; - - EnumSet options = EnumSet.noneOf(ConsumerImpl.Option.class); - - - boolean noLocal = false; - JMSSelectorFilter messageFilter = null; - - if(destination instanceof MessageSourceDestination) - { - _queue = ((MessageSourceDestination) _destination).getQueue(); - - if(_queue instanceof AMQQueue && ((AMQQueue)_queue).getAvailableAttributes().contains("topic")) - { - source.setDistributionMode(StdDistMode.COPY); - } - - Map filters = source.getFilter(); - - Map actualFilters = new HashMap(); - - if(filters != null) - { - for(Map.Entry entry : filters.entrySet()) - { - if(entry.getValue() instanceof NoLocalFilter) - { - actualFilters.put(entry.getKey(), entry.getValue()); - noLocal = true; - } - else if(messageFilter == null && entry.getValue() instanceof org.apache.qpid.amqp_1_0.type.messaging.JMSSelectorFilter) - { - - org.apache.qpid.amqp_1_0.type.messaging.JMSSelectorFilter selectorFilter = (org.apache.qpid.amqp_1_0.type.messaging.JMSSelectorFilter) entry.getValue(); - try - { - messageFilter = new JMSSelectorFilter(selectorFilter.getValue()); - - actualFilters.put(entry.getKey(), entry.getValue()); - } - catch (ParseException | SelectorParsingException e) - { - Error error = new Error(); - error.setCondition(AmqpError.INVALID_FIELD); - error.setDescription("Invalid JMS Selector: " + selectorFilter.getValue()); - error.setInfo(Collections.singletonMap(Symbol.valueOf("field"), Symbol.valueOf("filter"))); - throw new AmqpErrorException(error); - } - - - } - } - } - source.setFilter(actualFilters.isEmpty() ? null : actualFilters); - - _target = new ConsumerTarget_1_0(this, source.getDistributionMode() != StdDistMode.COPY); - if(source.getDistributionMode() != StdDistMode.COPY) - { - options.add(ConsumerImpl.Option.ACQUIRES); - options.add(ConsumerImpl.Option.SEES_REQUEUES); - } - - } - else if(destination instanceof ExchangeDestination) - { - try - { - - ExchangeDestination exchangeDestination = (ExchangeDestination) destination; - - boolean isDurable = exchangeDestination.getDurability() == TerminusDurability.CONFIGURATION - || exchangeDestination.getDurability() == TerminusDurability.UNSETTLED_STATE; - String name; - if(isDurable) - { - String remoteContainerId = getEndpoint().getSession().getConnection().getRemoteContainerId(); - remoteContainerId = remoteContainerId.replace("_","__").replace(".", "_:"); - - String endpointName = linkAttachment.getEndpoint().getName(); - endpointName = endpointName - .replace("_", "__") - .replace(".", "_:") - .replace("(", "_O") - .replace(")", "_C") - .replace("<", "_L") - .replace(">", "_R"); - name = "qpid_/" + remoteContainerId + "_/" + endpointName; - } - else - { - name = UUID.randomUUID().toString(); - } - - AMQQueue queue = _vhost.getQueue(name); - ExchangeImpl exchange = exchangeDestination.getExchange(); - - if(queue == null) - { - Map attributes = new HashMap(); - attributes.put(Queue.ID, UUID.randomUUID()); - attributes.put(Queue.NAME, name); - attributes.put(Queue.DURABLE, isDurable); - attributes.put(Queue.LIFETIME_POLICY, LifetimePolicy.DELETE_ON_NO_OUTBOUND_LINKS); - attributes.put(Queue.EXCLUSIVE, ExclusivityPolicy.LINK); - - queue = _vhost.createQueue(attributes); - } - else - { - Collection bindings = queue.getBindings(); - List bindingsToRemove = new ArrayList(); - for(BindingImpl existingBinding : bindings) - { - if(existingBinding.getExchange() != exchange) - { - bindingsToRemove.add(existingBinding); - } - } - for(BindingImpl existingBinding : bindingsToRemove) - { - existingBinding.delete(); - } - } - - - String binding = null; - - Map filters = source.getFilter(); - Map actualFilters = new HashMap(); - boolean hasBindingFilter = false; - if(filters != null && !filters.isEmpty()) - { - - for(Map.Entry entry : filters.entrySet()) - { - if(!hasBindingFilter - && entry.getValue() instanceof ExactSubjectFilter - && exchange.getType().equals(ExchangeDefaults.DIRECT_EXCHANGE_CLASS)) - { - ExactSubjectFilter filter = (ExactSubjectFilter) filters.values().iterator().next(); - source.setFilter(filters); - binding = filter.getValue(); - actualFilters.put(entry.getKey(), entry.getValue()); - hasBindingFilter = true; - } - else if(!hasBindingFilter - && entry.getValue() instanceof MatchingSubjectFilter - && exchange.getType().equals(ExchangeDefaults.TOPIC_EXCHANGE_CLASS)) - { - MatchingSubjectFilter filter = (MatchingSubjectFilter) filters.values().iterator().next(); - source.setFilter(filters); - binding = filter.getValue(); - actualFilters.put(entry.getKey(), entry.getValue()); - hasBindingFilter = true; - } - else if(entry.getValue() instanceof NoLocalFilter) - { - actualFilters.put(entry.getKey(), entry.getValue()); - noLocal = true; - } - else if(messageFilter == null && entry.getValue() instanceof org.apache.qpid.amqp_1_0.type.messaging.JMSSelectorFilter) - { - - org.apache.qpid.amqp_1_0.type.messaging.JMSSelectorFilter selectorFilter = (org.apache.qpid.amqp_1_0.type.messaging.JMSSelectorFilter) entry.getValue(); - try - { - messageFilter = new JMSSelectorFilter(selectorFilter.getValue()); - - actualFilters.put(entry.getKey(), entry.getValue()); - } - catch (ParseException | SelectorParsingException e) - { - Error error = new Error(); - error.setCondition(AmqpError.INVALID_FIELD); - error.setDescription("Invalid JMS Selector: " + selectorFilter.getValue()); - error.setInfo(Collections.singletonMap(Symbol.valueOf("field"), Symbol.valueOf("filter"))); - throw new AmqpErrorException(error); - } - - - } - } - } - _queue = queue; - source.setFilter(actualFilters.isEmpty() ? null : actualFilters); - if(binding != null) - { - exchange.addBinding(binding, queue,null); - } - if(exchangeDestination.getInitialRoutingAddress() != null) - { - exchange.addBinding(exchangeDestination.getInitialRoutingAddress(),queue,null); - } - if(binding == null - && exchangeDestination.getInitialRoutingAddress() == null - && exchange.getType().equals(ExchangeDefaults.FANOUT_EXCHANGE_CLASS)) - { - exchange.addBinding(queue.getName(), queue, null); - } - else if(binding == null - && exchangeDestination.getInitialRoutingAddress() == null - && exchange.getType().equals(ExchangeDefaults.TOPIC_EXCHANGE_CLASS)) - { - exchange.addBinding("#", queue, null); - } - - source.setDistributionMode(StdDistMode.COPY); - - qd = new QueueDestination(queue); - } - catch (QueueExistsException e) - { - _logger.error("A randomly generated temporary queue name collided with an existing queue",e); - throw new ConnectionScopedRuntimeException(e); - } - - - _target = new ConsumerTarget_1_0(this, true); - options.add(ConsumerImpl.Option.ACQUIRES); - options.add(ConsumerImpl.Option.SEES_REQUEUES); - - } - else - { - throw new ConnectionScopedRuntimeException("Unknown destination type"); - } - - if(_target != null) - { - if(noLocal) - { - options.add(ConsumerImpl.Option.NO_LOCAL); - } - - if(_durability == TerminusDurability.CONFIGURATION || - _durability == TerminusDurability.UNSETTLED_STATE ) - { - options.add(ConsumerImpl.Option.DURABLE); - } - - try - { - final String name; - if(getEndpoint().getTarget() instanceof Target) - { - Target target = (Target) getEndpoint().getTarget(); - name = target.getAddress() == null ? getEndpoint().getName() : target.getAddress(); - } - else - { - name = getEndpoint().getName(); - } - - FilterManager filters = null; - if(messageFilter != null) - { - filters = new FilterManager(); - filters.add(messageFilter.getName(), messageFilter); - } - - _consumer = _queue.addConsumer(_target, - filters, - Message_1_0.class, name, options); - } - catch (MessageSource.ExistingExclusiveConsumer e) - { - _logger.info("Cannot add a consumer to the destination as there is already an exclusive consumer"); - throw new ConnectionScopedRuntimeException(e); - } - catch (MessageSource.ExistingConsumerPreventsExclusive e) - { - _logger.info("Cannot add an exclusive consumer to the destination as there is already a consumer"); - throw new ConnectionScopedRuntimeException(e); - } - catch (MessageSource.ConsumerAccessRefused e) - { - _logger.info("Cannot add an exclusive consumer to the destination as there is an incompatible exclusivity policy"); - throw new ConnectionScopedRuntimeException(e); - } - } - - } - - public void resume(SendingLinkAttachment linkAttachment) - { - _linkAttachment = linkAttachment; - } - - public void remoteDetached(final LinkEndpoint endpoint, final Detach detach) - { - //TODO - // if not durable or close - if(Boolean.TRUE.equals(detach.getClosed()) - || !(TerminusDurability.UNSETTLED_STATE.equals(_durability)|| TerminusDurability.CONFIGURATION.equals(_durability))) - { - _consumer.close(); - - Modified state = new Modified(); - state.setDeliveryFailed(true); - - for(UnsettledAction action : _unsettledActionMap.values()) - { - - action.process(state,Boolean.TRUE); - } - _unsettledActionMap.clear(); - - endpoint.close(); - - if(_destination instanceof ExchangeDestination - && (_durability == TerminusDurability.CONFIGURATION - || _durability == TerminusDurability.UNSETTLED_STATE)) - { - try - { - _vhost.removeQueue((AMQQueue)_queue); - } - catch (AccessControlException e) - { - //TODO - _logger.error("Error registering subscription", e); - } - } - - if(_closeAction != null) - { - _closeAction.run(); - } - - } - else if(detach.getError() != null - && !_linkAttachment.getEndpoint().getSession().isSyntheticError(detach.getError())) - { - _linkAttachment = null; - _target.flowStateChanged(); - } - else - { - endpoint.detach(); - } - } - - public void start() - { - //TODO - } - - public SendingLinkEndpoint getEndpoint() - { - return _linkAttachment == null ? null : _linkAttachment.getEndpoint() ; - } - - public Session_1_0 getSession() - { - return _linkAttachment == null ? null : _linkAttachment.getSession(); - } - - public void flowStateChanged() - { - if(Boolean.TRUE.equals(getEndpoint().getDrain()) - && hasCredit()) - { - _draining = true; - _target.flush(); - } - - while(!_resumeAcceptedTransfers.isEmpty() && getEndpoint().hasCreditToSend()) - { - Accepted accepted = new Accepted(); - synchronized(getLock()) - { - - Transfer xfr = new Transfer(); - Binary dt = _resumeAcceptedTransfers.remove(0); - xfr.setDeliveryTag(dt); - xfr.setState(accepted); - xfr.setResume(Boolean.TRUE); - getEndpoint().transfer(xfr); - } - - } - if(_resumeAcceptedTransfers.isEmpty()) - { - _target.flowStateChanged(); - } - - } - - boolean hasCredit() - { - return getEndpoint().getLinkCredit().compareTo(UnsignedInteger.ZERO) > 0; - } - - public boolean isDraining() - { - return false; //TODO - } - - public boolean drained() - { - if(getEndpoint() != null) - { - synchronized(getEndpoint().getLock()) - { - if(_draining) - { - //TODO - getEndpoint().drained(); - _draining = false; - return true; - } - else - { - return false; - } - } - } - else - { - return false; - } - } - - public void addUnsettled(Binary tag, UnsettledAction unsettledAction, MessageInstance queueEntry) - { - _unsettledActionMap.put(tag,unsettledAction); - if(getTransactionId() == null) - { - _unsettledMap.put(tag, queueEntry); - } - } - - public void removeUnsettled(Binary tag) - { - _unsettledActionMap.remove(tag); - } - - public void handle(Binary deliveryTag, DeliveryState state, Boolean settled) - { - UnsettledAction action = _unsettledActionMap.get(deliveryTag); - boolean localSettle = false; - if(action != null) - { - localSettle = action.process(state, settled); - if(localSettle && !Boolean.TRUE.equals(settled)) - { - _linkAttachment.updateDisposition(deliveryTag, state, true); - } - } - if(Boolean.TRUE.equals(settled) || localSettle) - { - _unsettledActionMap.remove(deliveryTag); - _unsettledMap.remove(deliveryTag); - } - } - - ServerTransaction getTransaction(Binary transactionId) - { - return _linkAttachment.getSession().getTransaction(transactionId); - } - - public Binary getTransactionId() - { - SendingLinkEndpoint endpoint = getEndpoint(); - return endpoint == null ? null : endpoint.getTransactionId(); - } - - public synchronized Object getLock() - { - return _linkAttachment == null ? this : getEndpoint().getLock(); - } - - public boolean isDetached() - { - return _linkAttachment == null || getEndpoint().isDetached(); - } - - public boolean isAttached() - { - return _linkAttachment != null && getEndpoint().isAttached(); - } - - public synchronized void setLinkAttachment(SendingLinkAttachment linkAttachment) - { - - if(_consumer.isActive()) - { - _target.suspend(); - } - - _linkAttachment = linkAttachment; - - SendingLinkEndpoint endpoint = linkAttachment.getEndpoint(); - endpoint.setDeliveryStateHandler(this); - Map initialUnsettledMap = endpoint.getInitialUnsettledMap(); - Map unsettledCopy = new HashMap(_unsettledMap); - _resumeAcceptedTransfers.clear(); - _resumeFullTransfers.clear(); - - for(Map.Entry entry : unsettledCopy.entrySet()) - { - Binary deliveryTag = entry.getKey(); - final MessageInstance queueEntry = entry.getValue(); - if(initialUnsettledMap == null || !initialUnsettledMap.containsKey(deliveryTag)) - { - queueEntry.setRedelivered(); - queueEntry.release(); - _unsettledMap.remove(deliveryTag); - } - else if(initialUnsettledMap.get(deliveryTag) instanceof Outcome) - { - Outcome outcome = (Outcome) initialUnsettledMap.get(deliveryTag); - - if(outcome instanceof Accepted) - { - AutoCommitTransaction txn = new AutoCommitTransaction(_vhost.getMessageStore()); - if(_consumer.acquires()) - { - if(queueEntry.acquire() || queueEntry.isAcquired()) - { - txn.dequeue(Collections.singleton(queueEntry), - new ServerTransaction.Action() - { - public void postCommit() - { - queueEntry.delete(); - } - - public void onRollback() - { - } - }); - } - } - } - else if(outcome instanceof Released) - { - AutoCommitTransaction txn = new AutoCommitTransaction(_vhost.getMessageStore()); - if(_consumer.acquires()) - { - txn.dequeue(Collections.singleton(queueEntry), - new ServerTransaction.Action() - { - public void postCommit() - { - queueEntry.release(); - } - - public void onRollback() - { - //To change body of implemented methods use File | Settings | File Templates. - } - }); - } - } - //_unsettledMap.remove(deliveryTag); - initialUnsettledMap.remove(deliveryTag); - _resumeAcceptedTransfers.add(deliveryTag); - } - else - { - _resumeFullTransfers.add(queueEntry); - // exists in receivers map, but not yet got an outcome ... should resend with resume = true - } - // TODO - else - } - - - } - - public Map getUnsettledOutcomeMap() - { - Map unsettled = new HashMap(_unsettledMap); - - for(Map.Entry entry : unsettled.entrySet()) - { - entry.setValue(null); - } - - return unsettled; - } - - public void setCloseAction(Runnable action) - { - _closeAction = action; - } - - public VirtualHostImpl getVirtualHost() - { - return _vhost; - } - - public ConsumerImpl getConsumer() - { - return _consumer; - } - - public ConsumerTarget_1_0 getConsumerTarget() - { - return _target; - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Session_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Session_1_0.java deleted file mode 100644 index b65fe06980..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Session_1_0.java +++ /dev/null @@ -1,962 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.v1_0; - -import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.CHANNEL_FORMAT; - -import java.security.AccessControlException; -import java.security.PrivilegedAction; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicBoolean; - -import javax.security.auth.Subject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.amqp_1_0.transport.LinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.ReceivingLinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.ReceivingLinkListener; -import org.apache.qpid.amqp_1_0.transport.SendingLinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.SendingLinkListener; -import org.apache.qpid.amqp_1_0.transport.SessionEndpoint; -import org.apache.qpid.amqp_1_0.transport.SessionEventListener; -import org.apache.qpid.amqp_1_0.type.AmqpErrorException; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.LifetimePolicy; -import org.apache.qpid.amqp_1_0.type.Symbol; -import org.apache.qpid.amqp_1_0.type.messaging.DeleteOnClose; -import org.apache.qpid.amqp_1_0.type.messaging.DeleteOnNoLinks; -import org.apache.qpid.amqp_1_0.type.messaging.DeleteOnNoLinksOrMessages; -import org.apache.qpid.amqp_1_0.type.messaging.DeleteOnNoMessages; -import org.apache.qpid.amqp_1_0.type.messaging.Source; -import org.apache.qpid.amqp_1_0.type.messaging.Target; -import org.apache.qpid.amqp_1_0.type.messaging.TerminusDurability; -import org.apache.qpid.amqp_1_0.type.transaction.Coordinator; -import org.apache.qpid.amqp_1_0.type.transaction.TxnCapability; -import org.apache.qpid.amqp_1_0.type.transport.AmqpError; -import org.apache.qpid.amqp_1_0.type.transport.ConnectionError; -import org.apache.qpid.amqp_1_0.type.transport.Detach; -import org.apache.qpid.amqp_1_0.type.transport.End; -import org.apache.qpid.amqp_1_0.type.transport.Error; -import org.apache.qpid.amqp_1_0.type.transport.Role; -import org.apache.qpid.amqp_1_0.type.transport.Transfer; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.connection.SessionPrincipal; -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.exchange.ExchangeImpl; -import org.apache.qpid.server.logging.LogSubject; -import org.apache.qpid.server.message.MessageDestination; -import org.apache.qpid.server.message.MessageSource; -import org.apache.qpid.server.model.ConfigurationChangeListener; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.Consumer; -import org.apache.qpid.server.model.Session; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.protocol.ConsumerListener; -import org.apache.qpid.server.protocol.LinkRegistry; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.txn.AutoCommitTransaction; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; -import org.apache.qpid.server.virtualhost.QueueExistsException; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; - -public class Session_1_0 implements SessionEventListener, AMQSessionModel, LogSubject -{ - private static final Logger _logger = LoggerFactory.getLogger(Session_1_0.class); - private static final Symbol LIFETIME_POLICY = Symbol.valueOf("lifetime-policy"); - private final SessionEndpoint _endpoint; - private AutoCommitTransaction _transaction; - - private final LinkedHashMap _openTransactions = - new LinkedHashMap(); - - private final CopyOnWriteArrayList> _taskList = - new CopyOnWriteArrayList>(); - - private final Connection_1_0 _connection; - private UUID _id = UUID.randomUUID(); - private AtomicBoolean _closed = new AtomicBoolean(); - private final Subject _subject = new Subject(); - - private final CopyOnWriteArrayList> _consumers = new CopyOnWriteArrayList>(); - private final CopyOnWriteArrayList _sendingLinks = new CopyOnWriteArrayList<>(); - private final ConfigurationChangeListener _consumerClosedListener = new ConsumerClosedListener(); - private final CopyOnWriteArrayList _consumerListeners = new CopyOnWriteArrayList(); - private Session _modelObject; - - - public Session_1_0(final Connection_1_0 connection, final SessionEndpoint endpoint) - { - _endpoint = endpoint; - _connection = connection; - _subject.getPrincipals().addAll(connection.getSubject().getPrincipals()); - _subject.getPrincipals().add(new SessionPrincipal(this)); - } - - public void remoteLinkCreation(final LinkEndpoint endpoint) - { - - Destination destination; - Link_1_0 link = null; - Error error = null; - - final - LinkRegistry - linkRegistry = getVirtualHost().getLinkRegistry(endpoint.getSession().getConnection().getRemoteContainerId()); - - - if(endpoint.getRole() == Role.SENDER) - { - - final SendingLink_1_0 previousLink = (SendingLink_1_0) linkRegistry.getDurableSendingLink(endpoint.getName()); - - if(previousLink == null) - { - - Target target = (Target) endpoint.getTarget(); - Source source = (Source) endpoint.getSource(); - - - if(source != null) - { - if(Boolean.TRUE.equals(source.getDynamic())) - { - AMQQueue tempQueue = createTemporaryQueue(source.getDynamicNodeProperties()); - source.setAddress(tempQueue.getName()); - } - String addr = source.getAddress(); - if(!addr.startsWith("/") && addr.contains("/")) - { - String[] parts = addr.split("/",2); - ExchangeImpl exchg = getVirtualHost().getExchange(parts[0]); - if(exchg != null) - { - ExchangeDestination exchangeDestination = - new ExchangeDestination(exchg, source.getDurable(), source.getExpiryPolicy()); - exchangeDestination.setInitialRoutingAddress(parts[1]); - destination = exchangeDestination; - - } - else - { - endpoint.setSource(null); - destination = null; - } - } - else - { - MessageSource queue = getVirtualHost().getMessageSource(addr); - if(queue != null) - { - destination = new MessageSourceDestination(queue); - } - else - { - ExchangeImpl exchg = getVirtualHost().getExchange(addr); - if(exchg != null) - { - destination = new ExchangeDestination(exchg, source.getDurable(), source.getExpiryPolicy()); - } - else - { - endpoint.setSource(null); - destination = null; - } - } - } - - } - else - { - destination = null; - } - - if(destination != null) - { - final SendingLinkEndpoint sendingLinkEndpoint = (SendingLinkEndpoint) endpoint; - try - { - final SendingLink_1_0 sendingLink = new SendingLink_1_0(new SendingLinkAttachment(this, sendingLinkEndpoint), - getVirtualHost(), - (SendingDestination) destination - ); - - sendingLinkEndpoint.setLinkEventListener(new SubjectSpecificSendingLinkListener(sendingLink)); - registerConsumer(sendingLink); - - link = sendingLink; - if(TerminusDurability.UNSETTLED_STATE.equals(source.getDurable()) || TerminusDurability.CONFIGURATION.equals(source.getDurable())) - { - linkRegistry.registerSendingLink(endpoint.getName(), sendingLink); - } - } - catch(AmqpErrorException e) - { - _logger.error("Error creating sending link", e); - destination = null; - sendingLinkEndpoint.setSource(null); - error = e.getError(); - } - } - } - else - { - Source newSource = (Source) endpoint.getSource(); - - Source oldSource = (Source) previousLink.getEndpoint().getSource(); - final TerminusDurability newSourceDurable = newSource == null ? null : newSource.getDurable(); - if(newSourceDurable != null) - { - oldSource.setDurable(newSourceDurable); - if(newSourceDurable.equals(TerminusDurability.NONE)) - { - linkRegistry.unregisterSendingLink(endpoint.getName()); - } - } - endpoint.setSource(oldSource); - SendingLinkEndpoint sendingLinkEndpoint = (SendingLinkEndpoint) endpoint; - previousLink.setLinkAttachment(new SendingLinkAttachment(this, sendingLinkEndpoint)); - sendingLinkEndpoint.setLinkEventListener(new SubjectSpecificSendingLinkListener(previousLink)); - link = previousLink; - endpoint.setLocalUnsettled(previousLink.getUnsettledOutcomeMap()); - } - } - else - { - if(endpoint.getTarget() instanceof Coordinator) - { - Coordinator coordinator = (Coordinator) endpoint.getTarget(); - TxnCapability[] capabilities = coordinator.getCapabilities(); - boolean localTxn = false; - boolean multiplePerSession = false; - if(capabilities != null) - { - for(TxnCapability capability : capabilities) - { - if(capability.equals(TxnCapability.LOCAL_TXN)) - { - localTxn = true; - } - else if(capability.equals(TxnCapability.MULTI_TXNS_PER_SSN)) - { - multiplePerSession = true; - } - else - { - error = new Error(); - error.setCondition(AmqpError.NOT_IMPLEMENTED); - error.setDescription("Unsupported capability: " + capability); - break; - } - } - } - - /* if(!localTxn) - { - capabilities.add(TxnCapabilities.LOCAL_TXN); - }*/ - - final ReceivingLinkEndpoint receivingLinkEndpoint = (ReceivingLinkEndpoint) endpoint; - final TxnCoordinatorLink_1_0 coordinatorLink = - new TxnCoordinatorLink_1_0(getVirtualHost(), this, receivingLinkEndpoint, _openTransactions); - receivingLinkEndpoint.setLinkEventListener(new SubjectSpecificReceivingLinkListener(coordinatorLink)); - link = coordinatorLink; - - - } - else - { - - ReceivingLink_1_0 previousLink = - (ReceivingLink_1_0) linkRegistry.getDurableReceivingLink(endpoint.getName()); - - if(previousLink == null) - { - - Target target = (Target) endpoint.getTarget(); - - if(target != null) - { - if(Boolean.TRUE.equals(target.getDynamic())) - { - - AMQQueue tempQueue = createTemporaryQueue(target.getDynamicNodeProperties()); - target.setAddress(tempQueue.getName()); - } - - String addr = target.getAddress(); - if(!addr.startsWith("/") && addr.contains("/")) - { - String[] parts = addr.split("/",2); - ExchangeImpl exchange = getVirtualHost().getExchange(parts[0]); - if(exchange != null) - { - ExchangeDestination exchangeDestination = - new ExchangeDestination(exchange, - target.getDurable(), - target.getExpiryPolicy()); - - exchangeDestination.setInitialRoutingAddress(parts[1]); - - destination = exchangeDestination; - - } - else - { - endpoint.setTarget(null); - destination = null; - } - } - else - { - MessageDestination messageDestination = getVirtualHost().getMessageDestination(addr); - if(messageDestination != null) - { - destination = new NodeReceivingDestination(messageDestination, target.getDurable(), - target.getExpiryPolicy()); - } - else - { - AMQQueue queue = getVirtualHost().getQueue(addr); - if(queue != null) - { - - destination = new QueueDestination(queue); - } - else - { - endpoint.setTarget(null); - destination = null; - } - - } - } - - } - else - { - destination = null; - } - if(destination != null) - { - final ReceivingLinkEndpoint receivingLinkEndpoint = (ReceivingLinkEndpoint) endpoint; - final ReceivingLink_1_0 receivingLink = new ReceivingLink_1_0(new ReceivingLinkAttachment(this, receivingLinkEndpoint), - getVirtualHost(), - (ReceivingDestination) destination); - - receivingLinkEndpoint.setLinkEventListener(new SubjectSpecificReceivingLinkListener(receivingLink)); - - link = receivingLink; - if(TerminusDurability.UNSETTLED_STATE.equals(target.getDurable()) - || TerminusDurability.CONFIGURATION.equals(target.getDurable())) - { - linkRegistry.registerReceivingLink(endpoint.getName(), receivingLink); - } - } - } - else - { - ReceivingLinkEndpoint receivingLinkEndpoint = (ReceivingLinkEndpoint) endpoint; - previousLink.setLinkAttachment(new ReceivingLinkAttachment(this, receivingLinkEndpoint)); - receivingLinkEndpoint.setLinkEventListener(previousLink); - link = previousLink; - endpoint.setLocalUnsettled(previousLink.getUnsettledOutcomeMap()); - - } - } - } - - endpoint.attach(); - - if(link == null) - { - if(error == null) - { - error = new Error(); - error.setCondition(AmqpError.NOT_FOUND); - } - endpoint.close(error); - } - else - { - link.start(); - } - } - - private void registerConsumer(final SendingLink_1_0 link) - { - ConsumerImpl consumer = link.getConsumer(); - if(consumer instanceof Consumer) - { - Consumer modelConsumer = (Consumer) consumer; - _consumers.add(modelConsumer); - _sendingLinks.add(link); - modelConsumer.addChangeListener(_consumerClosedListener); - consumerAdded(modelConsumer); - } - } - - - private AMQQueue createTemporaryQueue(Map properties) - { - final String queueName = UUID.randomUUID().toString(); - AMQQueue queue = null; - try - { - LifetimePolicy lifetimePolicy = properties == null - ? null - : (LifetimePolicy) properties.get(LIFETIME_POLICY); - Map attributes = new HashMap(); - attributes.put(org.apache.qpid.server.model.Queue.ID, UUID.randomUUID()); - attributes.put(org.apache.qpid.server.model.Queue.NAME, queueName); - attributes.put(org.apache.qpid.server.model.Queue.DURABLE, false); - - if(lifetimePolicy instanceof DeleteOnNoLinks) - { - attributes.put(org.apache.qpid.server.model.Queue.LIFETIME_POLICY, - org.apache.qpid.server.model.LifetimePolicy.DELETE_ON_NO_LINKS); - } - else if(lifetimePolicy instanceof DeleteOnNoLinksOrMessages) - { - attributes.put(org.apache.qpid.server.model.Queue.LIFETIME_POLICY, - org.apache.qpid.server.model.LifetimePolicy.IN_USE); - } - else if(lifetimePolicy instanceof DeleteOnClose) - { - attributes.put(org.apache.qpid.server.model.Queue.LIFETIME_POLICY, - org.apache.qpid.server.model.LifetimePolicy.DELETE_ON_CONNECTION_CLOSE); - } - else if(lifetimePolicy instanceof DeleteOnNoMessages) - { - attributes.put(org.apache.qpid.server.model.Queue.LIFETIME_POLICY, - org.apache.qpid.server.model.LifetimePolicy.IN_USE); - } - else - { - attributes.put(org.apache.qpid.server.model.Queue.LIFETIME_POLICY, - org.apache.qpid.server.model.LifetimePolicy.DELETE_ON_CONNECTION_CLOSE); - } - - - // TODO convert AMQP 1-0 node properties to queue attributes - - queue = getVirtualHost().createQueue(attributes); - } - catch (AccessControlException e) - { - //TODO - _logger.info("Security error", e); - throw new ConnectionScopedRuntimeException(e); - } - catch (QueueExistsException e) - { - _logger.error("A temporary queue was created with a name which collided with an existing queue name"); - throw new ConnectionScopedRuntimeException(e); - } - - return queue; - } - - public ServerTransaction getTransaction(Binary transactionId) - { - // TODO should treat invalid id differently to null - ServerTransaction transaction = _openTransactions.get(binaryToInteger(transactionId)); - if(transaction == null) - { - if(_transaction == null) - { - _transaction = new AutoCommitTransaction(_connection.getVirtualHost().getMessageStore()); - } - transaction = _transaction; - } - return transaction; - } - - public void remoteEnd(End end) - { - Iterator> iter = _openTransactions.entrySet().iterator(); - - while(iter.hasNext()) - { - Map.Entry entry = iter.next(); - entry.getValue().rollback(); - iter.remove(); - } - - for(LinkEndpoint linkEndpoint : _endpoint.getLocalLinkEndpoints()) - { - linkEndpoint.remoteDetached(new Detach()); - } - - _connection.sessionEnded(this); - performCloseTasks(); - if(_modelObject != null) - { - _modelObject.delete(); - } - - } - - Integer binaryToInteger(final Binary txnId) - { - if(txnId == null) - { - return null; - } - - if(txnId.getLength() > 4) - throw new IllegalArgumentException(); - - int id = 0; - byte[] data = txnId.getArray(); - for(int i = 0; i < txnId.getLength(); i++) - { - id <<= 8; - id += ((int)data[i+txnId.getArrayOffset()] & 0xff); - } - - return id; - - } - - Binary integerToBinary(final int txnId) - { - byte[] data = new byte[4]; - data[3] = (byte) (txnId & 0xff); - data[2] = (byte) ((txnId & 0xff00) >> 8); - data[1] = (byte) ((txnId & 0xff0000) >> 16); - data[0] = (byte) ((txnId & 0xff000000) >> 24); - return new Binary(data); - - } - - @Override - public UUID getId() - { - return _id; - } - - @Override - public Connection_1_0 getConnectionModel() - { - return _connection; - } - - @Override - public String getClientID() - { - // TODO - return ""; - } - - @Override - public void close() - { - performCloseTasks(); - _endpoint.end(); - if(_modelObject != null) - { - _modelObject.delete(); - } - } - - protected void performCloseTasks() - { - - if(_closed.compareAndSet(false, true)) - { - List> taskList = new ArrayList>(_taskList); - _taskList.clear(); - for(Action task : taskList) - { - task.performAction(this); - } - } - } - - - @Override - public void close(AMQConstant cause, String message) - { - performCloseTasks(); - final End end = new End(); - final Error theError = new Error(); - theError.setDescription(message); - theError.setCondition(ConnectionError.CONNECTION_FORCED); - end.setError(theError); - _endpoint.end(end); - } - - @Override - public void transportStateChanged() - { - for(SendingLink_1_0 link : _sendingLinks) - { - ConsumerTarget_1_0 target = link.getConsumerTarget(); - target.flowStateChanged(); - - - } - - - } - - @Override - public LogSubject getLogSubject() - { - return this; - } - - @Override - public void checkTransactionStatus(long openWarn, long openClose, long idleWarn, long idleClose) - { - // TODO - required for AMQSessionModel / long running transaction detection - } - - @Override - public void block(AMQQueue queue) - { - // TODO - required for AMQSessionModel / producer side flow control - } - - @Override - public void unblock(AMQQueue queue) - { - // TODO - required for AMQSessionModel / producer side flow control - } - - @Override - public void block() - { - // TODO - required for AMQSessionModel / producer side flow control - } - - @Override - public void unblock() - { - // TODO - required for AMQSessionModel / producer side flow control - } - - @Override - public boolean getBlocking() - { - // TODO - return false; - } - - @Override - public Object getConnectionReference() - { - return getConnection().getReference(); - } - - @Override - public int getUnacknowledgedMessageCount() - { - // TODO - return 0; - } - - @Override - public Long getTxnCount() - { - // TODO - return 0l; - } - - @Override - public Long getTxnStart() - { - // TODO - return 0l; - } - - @Override - public Long getTxnCommits() - { - // TODO - return 0l; - } - - @Override - public Long getTxnRejects() - { - // TODO - return 0l; - } - - @Override - public int getChannelId() - { - return _endpoint.getSendingChannel(); - } - - @Override - public int getConsumerCount() - { - return getConsumers().size(); - } - - - - public String toLogString() - { - long connectionId = getConnectionModel().getConnectionId(); - - String remoteAddress = getConnectionModel().getRemoteAddressString(); - - return "[" + - MessageFormat.format(CHANNEL_FORMAT, - connectionId, - getClientID(), - remoteAddress, - getVirtualHost().getName(), - _endpoint.getSendingChannel()) + "] "; - } - - @Override - public int compareTo(AMQSessionModel o) - { - return getId().compareTo(o.getId()); - } - - public Connection_1_0 getConnection() - { - return _connection; - } - - @Override - public void addDeleteTask(final Action task) - { - if(!_closed.get()) - { - _taskList.add(task); - } - } - - @Override - public void removeDeleteTask(final Action task) - { - _taskList.remove(task); - } - - public Subject getSubject() - { - return _subject; - } - - VirtualHostImpl getVirtualHost() - { - return _connection.getVirtualHost(); - } - - - private class SubjectSpecificReceivingLinkListener implements ReceivingLinkListener - { - private final ReceivingLinkListener _linkListener; - - public SubjectSpecificReceivingLinkListener(final ReceivingLinkListener linkListener) - { - _linkListener = linkListener; - } - - @Override - public void messageTransfer(final Transfer xfr) - { - Subject.doAs(_subject, new PrivilegedAction() - { - @Override - public Object run() - { - _linkListener.messageTransfer(xfr); - return null; - } - }); - } - - @Override - public void remoteDetached(final LinkEndpoint endpoint, final Detach detach) - { - Subject.doAs(_subject, new PrivilegedAction() - { - @Override - public Object run() - { - _linkListener.remoteDetached(endpoint, detach); - return null; - } - }); - } - } - - private class SubjectSpecificSendingLinkListener implements SendingLinkListener - { - private final SendingLink_1_0 _previousLink; - - public SubjectSpecificSendingLinkListener(final SendingLink_1_0 previousLink) - { - _previousLink = previousLink; - } - - @Override - public void flowStateChanged() - { - Subject.doAs(_subject, new PrivilegedAction() - { - @Override - public Object run() - { - _previousLink.flowStateChanged(); - return null; - } - }); - } - - @Override - public void remoteDetached(final LinkEndpoint endpoint, final Detach detach) - { - Subject.doAs(_subject, new PrivilegedAction() - { - @Override - public Object run() - { - _previousLink.remoteDetached(endpoint, detach); - return null; - } - }); - } - } - - - @Override - public Collection> getConsumers() - { - return Collections.unmodifiableCollection(_consumers); - } - - @Override - public void addConsumerListener(final ConsumerListener listener) - { - _consumerListeners.add(listener); - } - - @Override - public void removeConsumerListener(final ConsumerListener listener) - { - _consumerListeners.remove(listener); - } - - @Override - public void setModelObject(final Session session) - { - _modelObject = session; - } - - @Override - public Session getModelObject() - { - return _modelObject; - } - - @Override - public long getTransactionStartTime() - { - return 0L; - } - - @Override - public long getTransactionUpdateTime() - { - return 0L; - } - - @Override - public void processPending() - { - for(Consumer consumer : getConsumers()) - { - - ((ConsumerImpl)consumer).getTarget().processPending(); - } - } - - private void consumerAdded(Consumer consumer) - { - for(ConsumerListener l : _consumerListeners) - { - l.consumerAdded(consumer); - } - } - - private void consumerRemoved(Consumer consumer) - { - for(ConsumerListener l : _consumerListeners) - { - l.consumerRemoved(consumer); - } - } - - private class ConsumerClosedListener implements ConfigurationChangeListener - { - @Override - public void stateChanged(final ConfiguredObject object, final org.apache.qpid.server.model.State oldState, final org.apache.qpid.server.model.State newState) - { - if(newState == org.apache.qpid.server.model.State.DELETED) - { - consumerRemoved((Consumer)object); - } - } - - @Override - public void childAdded(final ConfiguredObject object, final ConfiguredObject child) - { - - } - - @Override - public void childRemoved(final ConfiguredObject object, final ConfiguredObject child) - { - - } - - @Override - public void attributeSet(final ConfiguredObject object, - final String attributeName, - final Object oldAttributeValue, - final Object newAttributeValue) - { - - } - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/TxnCoordinatorLink_1_0.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/TxnCoordinatorLink_1_0.java deleted file mode 100644 index 2d60291c2f..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/TxnCoordinatorLink_1_0.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.protocol.v1_0; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.amqp_1_0.messaging.SectionDecoder; -import org.apache.qpid.amqp_1_0.messaging.SectionDecoderImpl; -import org.apache.qpid.amqp_1_0.transport.LinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.ReceivingLinkEndpoint; -import org.apache.qpid.amqp_1_0.transport.ReceivingLinkListener; -import org.apache.qpid.amqp_1_0.type.AmqpErrorException; -import org.apache.qpid.amqp_1_0.type.DeliveryState; -import org.apache.qpid.amqp_1_0.type.Section; -import org.apache.qpid.amqp_1_0.type.UnsignedInteger; -import org.apache.qpid.amqp_1_0.type.messaging.Accepted; -import org.apache.qpid.amqp_1_0.type.messaging.AmqpValue; -import org.apache.qpid.amqp_1_0.type.transaction.Declare; -import org.apache.qpid.amqp_1_0.type.transaction.Declared; -import org.apache.qpid.amqp_1_0.type.transaction.Discharge; -import org.apache.qpid.amqp_1_0.type.transport.AmqpError; -import org.apache.qpid.amqp_1_0.type.transport.Detach; -import org.apache.qpid.amqp_1_0.type.transport.Error; -import org.apache.qpid.amqp_1_0.type.transport.Transfer; -import org.apache.qpid.server.txn.LocalTransaction; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; - -public class TxnCoordinatorLink_1_0 implements ReceivingLinkListener, Link_1_0 -{ - private static final Logger _logger = LoggerFactory.getLogger(TxnCoordinatorLink_1_0.class); - private VirtualHostImpl _vhost; - private ReceivingLinkEndpoint _endpoint; - - private ArrayList _incompleteMessage; - private SectionDecoder _sectionDecoder; - private LinkedHashMap _openTransactions; - private Session_1_0 _session; - - - public TxnCoordinatorLink_1_0(VirtualHostImpl vhost, - Session_1_0 session_1_0, ReceivingLinkEndpoint endpoint, - LinkedHashMap openTransactions) - { - _vhost = vhost; - _session = session_1_0; - _endpoint = endpoint; - _sectionDecoder = new SectionDecoderImpl(endpoint.getSession().getConnection().getDescribedTypeRegistry()); - _openTransactions = openTransactions; - } - - public void messageTransfer(Transfer xfr) - { - // TODO - cope with fragmented messages - - ByteBuffer payload = null; - - - if(Boolean.TRUE.equals(xfr.getMore()) && _incompleteMessage == null) - { - _incompleteMessage = new ArrayList(); - _incompleteMessage.add(xfr); - return; - } - else if(_incompleteMessage != null) - { - _incompleteMessage.add(xfr); - if(Boolean.TRUE.equals(xfr.getMore())) - { - return; - } - - int size = 0; - for(Transfer t : _incompleteMessage) - { - size += t.getPayload().limit(); - } - payload = ByteBuffer.allocate(size); - for(Transfer t : _incompleteMessage) - { - payload.put(t.getPayload().duplicate()); - } - payload.flip(); - _incompleteMessage=null; - - } - else - { - payload = xfr.getPayload(); - } - - - // Only interested int he amqp-value section that holds the message to the coordinator - try - { - List
sections = _sectionDecoder.parseAll(payload); - - for(Section section : sections) - { - if(section instanceof AmqpValue) - { - Object command = ((AmqpValue) section).getValue(); - - if(command instanceof Declare) - { - Integer txnId = Integer.valueOf(0); - Iterator existingTxn = _openTransactions.keySet().iterator(); - while(existingTxn.hasNext()) - { - txnId = existingTxn.next(); - } - txnId = Integer.valueOf(txnId.intValue() + 1); - - _openTransactions.put(txnId, new LocalTransaction(_vhost.getMessageStore())); - - Declared state = new Declared(); - - - - state.setTxnId(_session.integerToBinary(txnId)); - _endpoint.updateDisposition(xfr.getDeliveryTag(), state, true); - - } - else if(command instanceof Discharge) - { - Discharge discharge = (Discharge) command; - - DeliveryState state = xfr.getState(); - discharge(_session.binaryToInteger(discharge.getTxnId()), discharge.getFail()); - _endpoint.updateDisposition(xfr.getDeliveryTag(), new Accepted(), true); - - } - } - } - - } - catch (AmqpErrorException e) - { - //TODO - _logger.error("AMQP error", e); - } - - } - - public void remoteDetached(LinkEndpoint endpoint, Detach detach) - { - //TODO - endpoint.detach(); - } - - private Error discharge(Integer transactionId, boolean fail) - { - Error error = null; - ServerTransaction txn = _openTransactions.get(transactionId); - if(txn != null) - { - if(fail) - { - txn.rollback(); - } - else - { - txn.commit(); - } - _openTransactions.remove(transactionId); - } - else - { - error = new Error(); - error.setCondition(AmqpError.NOT_FOUND); - error.setDescription("Unknown transactionId" + transactionId); - } - return error; - } - - - - public void start() - { - _endpoint.setLinkCredit(UnsignedInteger.ONE); - _endpoint.setCreditWindow(); - } -} diff --git a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/UnsettledAction.java b/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/UnsettledAction.java deleted file mode 100644 index 0fee4086b4..0000000000 --- a/qpid/java/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/UnsettledAction.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.protocol.v1_0; - -import org.apache.qpid.amqp_1_0.type.DeliveryState; - -public interface UnsettledAction -{ - boolean process(DeliveryState state, Boolean settled); -} diff --git a/qpid/java/broker-plugins/amqp-msg-conv-0-10-to-1-0/pom.xml b/qpid/java/broker-plugins/amqp-msg-conv-0-10-to-1-0/pom.xml deleted file mode 100644 index 6349661ad9..0000000000 --- a/qpid/java/broker-plugins/amqp-msg-conv-0-10-to-1-0/pom.xml +++ /dev/null @@ -1,75 +0,0 @@ - - - - 4.0.0 - - - org.apache.qpid - qpid-java-build - 0.32-SNAPSHOT - ../../pom.xml - - - qpid-broker-plugins-amqp-msg-conv-0-10-to-1-0 - Qpid AMQP 0-10 to 1-0 Message Conversion Broker Plug-in - AMQP message conversion (0-10 to 1-0) broker plug-in - - - - org.apache.qpid - qpid-broker-core - ${project.version} - provided - - - - org.apache.qpid - qpid-broker-codegen - ${project.version} - true - - - - org.apache.qpid - qpid-common - ${project.version} - - - - org.apache.qpid - qpid-broker-plugins-amqp-0-10-protocol - ${project.version} - - - - org.apache.qpid - qpid-amqp-1-0-common - ${project.version} - - - - org.apache.qpid - qpid-broker-plugins-amqp-1-0-protocol - ${project.version} - - - - - - - diff --git a/qpid/java/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_0_10_to_1_0.java b/qpid/java/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_0_10_to_1_0.java deleted file mode 100644 index 506e6b1850..0000000000 --- a/qpid/java/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_0_10_to_1_0.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.server.protocol.converter.v0_10_v1_0; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.apache.qpid.amqp_1_0.messaging.SectionEncoder; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.Section; -import org.apache.qpid.amqp_1_0.type.Symbol; -import org.apache.qpid.amqp_1_0.type.UnsignedByte; -import org.apache.qpid.amqp_1_0.type.UnsignedInteger; -import org.apache.qpid.amqp_1_0.type.messaging.ApplicationProperties; -import org.apache.qpid.amqp_1_0.type.messaging.Header; -import org.apache.qpid.amqp_1_0.type.messaging.Properties; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.protocol.v0_10.MessageTransferMessage; -import org.apache.qpid.server.protocol.v1_0.MessageConverter_to_1_0; -import org.apache.qpid.server.protocol.v1_0.MessageMetaData_1_0; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.MessageDeliveryMode; -import org.apache.qpid.transport.MessageProperties; - -@PluggableService -public class MessageConverter_0_10_to_1_0 extends MessageConverter_to_1_0 -{ - @Override - public Class getInputClass() - { - return MessageTransferMessage.class; - } - - - @Override - protected MessageMetaData_1_0 convertMetaData(MessageTransferMessage serverMessage, - SectionEncoder sectionEncoder) - { - List
sections = new ArrayList
(3); - final MessageProperties msgProps = serverMessage.getHeader().getMessageProperties(); - final DeliveryProperties deliveryProps = serverMessage.getHeader().getDeliveryProperties(); - - Header header = new Header(); - if(deliveryProps != null) - { - header.setDurable(deliveryProps.hasDeliveryMode() && deliveryProps.getDeliveryMode() == MessageDeliveryMode.PERSISTENT); - if(deliveryProps.hasPriority()) - { - header.setPriority(UnsignedByte.valueOf((byte) deliveryProps.getPriority().getValue())); - } - if(deliveryProps.hasTtl()) - { - header.setTtl(UnsignedInteger.valueOf(deliveryProps.getTtl())); - } - sections.add(header); - } - - Properties props = new Properties(); - - /* - TODO: the current properties are not currently set: - - absoluteExpiryTime - creationTime - groupId - groupSequence - replyToGroupId - to - */ - - if(msgProps != null) - { - if(msgProps.hasContentEncoding()) - { - props.setContentEncoding(Symbol.valueOf(msgProps.getContentEncoding())); - } - - if(msgProps.hasCorrelationId()) - { - props.setCorrelationId(msgProps.getCorrelationId()); - } - - if(msgProps.hasMessageId()) - { - props.setMessageId(msgProps.getMessageId()); - } - if(msgProps.hasReplyTo()) - { - props.setReplyTo(msgProps.getReplyTo().getExchange()+"/"+msgProps.getReplyTo().getRoutingKey()); - } - if(msgProps.hasContentType()) - { - props.setContentType(Symbol.valueOf(msgProps.getContentType())); - - // Modify the content type when we are dealing with java object messages produced by the Qpid 0.x client - if(props.getContentType() == Symbol.valueOf("application/java-object-stream")) - { - props.setContentType(Symbol.valueOf("application/x-java-serialized-object")); - } - } - - props.setSubject(serverMessage.getInitialRoutingAddress()); - - if(msgProps.hasUserId()) - { - props.setUserId(new Binary(msgProps.getUserId())); - } - - sections.add(props); - - Map applicationProperties = msgProps.getApplicationHeaders(); - - if(applicationProperties != null) - { - if(applicationProperties.containsKey("qpid.subject")) - { - props.setSubject(String.valueOf(applicationProperties.get("qpid.subject"))); - applicationProperties = new LinkedHashMap<>(applicationProperties); - applicationProperties.remove("qpid.subject"); - } - sections.add(new ApplicationProperties(applicationProperties)); - - } - } - return new MessageMetaData_1_0(sections, sectionEncoder); - } - - @Override - public String getType() - { - return "v0-10 to v1-0"; - } -} diff --git a/qpid/java/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_1_0_to_v0_10.java b/qpid/java/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_1_0_to_v0_10.java deleted file mode 100644 index 789789ac33..0000000000 --- a/qpid/java/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_1_0_to_v0_10.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.server.protocol.converter.v0_10_v1_0; - -import java.nio.ByteBuffer; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.protocol.v0_10.MessageMetaData_0_10; -import org.apache.qpid.server.protocol.v0_10.MessageTransferMessage; -import org.apache.qpid.server.protocol.v1_0.MessageConverter_from_1_0; -import org.apache.qpid.server.protocol.v1_0.MessageMetaData_1_0; -import org.apache.qpid.server.protocol.v1_0.Message_1_0; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.Header; -import org.apache.qpid.transport.MessageDeliveryPriority; -import org.apache.qpid.transport.MessageProperties; -import org.apache.qpid.transport.ReplyTo; - -@PluggableService -public class MessageConverter_1_0_to_v0_10 implements MessageConverter -{ - - public Class getInputClass() - { - return Message_1_0.class; - } - - @Override - public Class getOutputClass() - { - return MessageTransferMessage.class; - } - - @Override - public MessageTransferMessage convert(Message_1_0 serverMsg, VirtualHostImpl vhost) - { - return new MessageTransferMessage(convertToStoredMessage(serverMsg, vhost), null); - } - - private StoredMessage convertToStoredMessage(final Message_1_0 serverMsg, - final VirtualHostImpl vhost) - { - Object bodyObject = MessageConverter_from_1_0.convertBodyToObject(serverMsg); - - final byte[] messageContent = MessageConverter_from_1_0.convertToBody(bodyObject); - - final MessageMetaData_0_10 messageMetaData_0_10 = convertMetaData(serverMsg, - vhost, - MessageConverter_from_1_0.getBodyMimeType(bodyObject), - messageContent.length); - - return new StoredMessage() - { - @Override - public MessageMetaData_0_10 getMetaData() - { - return messageMetaData_0_10; - } - - @Override - public long getMessageNumber() - { - return serverMsg.getMessageNumber(); - } - - @Override - public int getContent(int offsetInMessage, ByteBuffer dst) - { - int size = messageContent.length - offsetInMessage; - if(dst.remaining() < size) - { - size = dst.remaining(); - } - ByteBuffer buf = ByteBuffer.wrap(messageContent, offsetInMessage, size); - dst.put(buf); - return size; - } - - @Override - public ByteBuffer getContent(int offsetInMessage, int size) - { - return ByteBuffer.wrap(messageContent, offsetInMessage, size); - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isInMemory() - { - return true; - } - - @Override - public boolean flowToDisk() - { - return false; - } - }; - } - - private MessageMetaData_0_10 convertMetaData(Message_1_0 serverMsg, - final VirtualHostImpl vhost, - final String bodyMimeType, - final int size) - { - DeliveryProperties deliveryProps = new DeliveryProperties(); - MessageProperties messageProps = new MessageProperties(); - - final MessageMetaData_1_0.MessageHeader_1_0 origHeader = serverMsg.getMessageHeader(); - - - deliveryProps.setExpiration(serverMsg.getExpiration()); - deliveryProps.setPriority(MessageDeliveryPriority.get(origHeader.getPriority())); - deliveryProps.setRoutingKey(serverMsg.getInitialRoutingAddress()); - deliveryProps.setTimestamp(origHeader.getTimestamp()); - - messageProps.setContentEncoding(origHeader.getEncoding()); - messageProps.setContentLength(size); - messageProps.setContentType(bodyMimeType); - if(origHeader.getCorrelationId() != null) - { - messageProps.setCorrelationId(origHeader.getCorrelationId().getBytes()); - } - final String origReplyTo = origHeader.getReplyTo(); - if(origReplyTo != null && !origReplyTo.equals("")) - { - ReplyTo replyTo; - if(origReplyTo.startsWith("/")) - { - replyTo = new ReplyTo("",origReplyTo); - } - else if(origReplyTo.contains("/")) - { - String[] parts = origReplyTo.split("/",2); - replyTo = new ReplyTo(parts[0],parts[1]); - } - else if(vhost.getExchange(origReplyTo) != null) - { - replyTo = new ReplyTo(origReplyTo,""); - } - else - { - replyTo = new ReplyTo("",origReplyTo); - } - messageProps.setReplyTo(replyTo); - } - - Map appHeaders = - (Map) MessageConverter_from_1_0.convertValue(serverMsg.getMessageHeader() - .getHeadersAsMap()); - if(origHeader.getSubject() != null && !appHeaders.containsKey("qpid.subject")) - { - appHeaders = new LinkedHashMap<>(appHeaders); - appHeaders.put("qpid.subject", origHeader.getSubject()); - } - messageProps.setApplicationHeaders(appHeaders); - - Header header = new Header(deliveryProps, messageProps, null); - return new MessageMetaData_0_10(header, size, serverMsg.getArrivalTime()); - } - - - - @Override - public String getType() - { - return "v1-0 to v0-10"; - } - - -} diff --git a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-0-10/pom.xml b/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-0-10/pom.xml deleted file mode 100644 index 560c916063..0000000000 --- a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-0-10/pom.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - - 4.0.0 - - - org.apache.qpid - qpid-java-build - 0.32-SNAPSHOT - ../../pom.xml - - - qpid-broker-plugins-amqp-msg-conv-0-8-to-0-10 - Qpid AMQP 0-8 to 0-10 Message Conversion Broker Plug-in - AMQP message conversion (0-8, 0-9 and 0-9-1 to 0-10) broker plug-in - - - - org.apache.qpid - qpid-broker-core - ${project.version} - provided - - - - org.apache.qpid - qpid-broker-codegen - ${project.version} - true - - - - org.apache.qpid - qpid-common - ${project.version} - - - - org.apache.qpid - qpid-broker-plugins-amqp-0-8-protocol - ${project.version} - - - - org.apache.qpid - qpid-broker-plugins-amqp-0-10-protocol - ${project.version} - - - - - - - diff --git a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_10_to_0_8.java b/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_10_to_0_8.java deleted file mode 100644 index a9637e9d4e..0000000000 --- a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_10_to_0_8.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.server.protocol.converter.v0_8_v0_10; - -import java.nio.ByteBuffer; -import java.util.HashMap; -import java.util.Map; - -import org.apache.qpid.AMQPInvalidClassException; -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.MessagePublishInfo; -import org.apache.qpid.server.exchange.ExchangeImpl; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.protocol.v0_10.MessageTransferMessage; -import org.apache.qpid.server.protocol.v0_8.AMQMessage; -import org.apache.qpid.server.protocol.v0_8.MessageMetaData; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.Header; -import org.apache.qpid.transport.MessageDeliveryMode; -import org.apache.qpid.transport.MessageProperties; -import org.apache.qpid.transport.ReplyTo; - -@PluggableService -public class MessageConverter_0_10_to_0_8 implements MessageConverter -{ - private static final int BASIC_CLASS_ID = 60; - - public static BasicContentHeaderProperties convertContentHeaderProperties(MessageTransferMessage messageTransferMessage, - VirtualHostImpl vhost) - { - BasicContentHeaderProperties props = new BasicContentHeaderProperties(); - - Header header = messageTransferMessage.getHeader(); - DeliveryProperties deliveryProps = header.getDeliveryProperties(); - MessageProperties messageProps = header.getMessageProperties(); - - if(deliveryProps != null) - { - if(deliveryProps.hasDeliveryMode()) - { - props.setDeliveryMode((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("ID:" + messageProps.getMessageId().toString()); - } - if(messageProps.hasReplyTo()) - { - ReplyTo replyTo = messageProps.getReplyTo(); - String exchangeName = replyTo.getExchange(); - String routingKey = replyTo.getRoutingKey(); - if(exchangeName == null) - { - exchangeName = ""; - } - - ExchangeImpl exchange = vhost.getExchange(exchangeName); - String exchangeClass = exchange == null - ? ExchangeDefaults.DIRECT_EXCHANGE_CLASS - : exchange.getType(); - props.setReplyTo(exchangeClass + "://" + exchangeName + "//?routingkey='" + (routingKey == null - ? "" - : routingKey + "'")); - - } - if(messageProps.hasUserId()) - { - props.setUserId(new AMQShortString(messageProps.getUserId())); - } - - if(messageProps.hasApplicationHeaders()) - { - Map appHeaders = new HashMap(messageProps.getApplicationHeaders()); - if(messageProps.getApplicationHeaders().containsKey("x-jms-type")) - { - props.setType(String.valueOf(appHeaders.remove("x-jms-type"))); - } - - FieldTable ft = new FieldTable(); - for(Map.Entry entry : appHeaders.entrySet()) - { - try - { - ft.put(AMQShortString.validValueOf(entry.getKey()), entry.getValue()); - } - catch (AMQPInvalidClassException e) - { - // TODO - // log here, but ignore - just can;t convert - } - } - props.setHeaders(ft); - - } - } - - return props; - } - - @Override - public Class getInputClass() - { - return MessageTransferMessage.class; - } - - @Override - public Class getOutputClass() - { - return AMQMessage.class; - } - - @Override - public AMQMessage convert(MessageTransferMessage message, VirtualHostImpl vhost) - { - return new AMQMessage(convertToStoredMessage(message, vhost)); - } - - private StoredMessage convertToStoredMessage(final MessageTransferMessage message, - VirtualHostImpl vhost) - { - final MessageMetaData metaData = convertMetaData(message, vhost); - return new StoredMessage() - { - @Override - public MessageMetaData getMetaData() - { - return metaData; - } - - @Override - public long getMessageNumber() - { - return message.getMessageNumber(); - } - - @Override - public int getContent(int offsetInMessage, ByteBuffer dst) - { - return message.getContent(dst, offsetInMessage); - } - - @Override - public ByteBuffer getContent(int offsetInMessage, int size) - { - return message.getContent(offsetInMessage, size); - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isInMemory() - { - return true; - } - - @Override - public boolean flowToDisk() - { - return false; - } - }; - } - - private MessageMetaData convertMetaData(MessageTransferMessage message, VirtualHostImpl vhost) - { - return new MessageMetaData(convertPublishBody(message), - convertContentHeaderBody(message, vhost), - message.getArrivalTime()); - } - - private ContentHeaderBody convertContentHeaderBody(MessageTransferMessage message, VirtualHostImpl vhost) - { - BasicContentHeaderProperties props = convertContentHeaderProperties(message, vhost); - ContentHeaderBody chb = new ContentHeaderBody(props); - chb.setBodySize(message.getSize()); - return chb; - } - - private MessagePublishInfo convertPublishBody(MessageTransferMessage message) - { - DeliveryProperties delvProps = message.getHeader().getDeliveryProperties(); - final AMQShortString exchangeName = (delvProps == null || delvProps.getExchange() == null) - ? null - : new AMQShortString(delvProps.getExchange()); - final AMQShortString routingKey = (delvProps == null || delvProps.getRoutingKey() == null) - ? null - : new AMQShortString(delvProps.getRoutingKey()); - final boolean immediate = delvProps != null && delvProps.getImmediate(); - final boolean mandatory = delvProps != null && !delvProps.getDiscardUnroutable(); - - return new MessagePublishInfo(exchangeName, immediate, mandatory, routingKey); - } - - @Override - public String getType() - { - return "v0-10 to v0-8"; - } -} diff --git a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_8_to_0_10.java b/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_8_to_0_10.java deleted file mode 100644 index ee16d96d5b..0000000000 --- a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_8_to_0_10.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.server.protocol.converter.v0_8_v0_10; - -import java.net.URISyntaxException; -import java.nio.ByteBuffer; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.protocol.v0_10.MessageMetaData_0_10; -import org.apache.qpid.server.protocol.v0_10.MessageTransferMessage; -import org.apache.qpid.server.protocol.v0_8.AMQMessage; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.Header; -import org.apache.qpid.transport.MessageDeliveryPriority; -import org.apache.qpid.transport.MessageProperties; -import org.apache.qpid.transport.ReplyTo; -import org.apache.qpid.url.AMQBindingURL; - -@PluggableService -public class MessageConverter_0_8_to_0_10 implements MessageConverter -{ - @Override - public Class getInputClass() - { - return AMQMessage.class; - } - - @Override - public Class getOutputClass() - { - return MessageTransferMessage.class; - } - - @Override - public MessageTransferMessage convert(AMQMessage message_0_8, VirtualHostImpl vhost) - { - return new MessageTransferMessage(convertToStoredMessage(message_0_8), null); - } - - private StoredMessage convertToStoredMessage(final AMQMessage message_0_8) - { - final MessageMetaData_0_10 messageMetaData_0_10 = convertMetaData(message_0_8); - return new StoredMessage() - { - @Override - public MessageMetaData_0_10 getMetaData() - { - return messageMetaData_0_10; - } - - @Override - public long getMessageNumber() - { - return message_0_8.getMessageNumber(); - } - - @Override - public int getContent(int offsetInMessage, ByteBuffer dst) - { - return message_0_8.getContent(dst, offsetInMessage); - } - - @Override - public ByteBuffer getContent(int offsetInMessage, int size) - { - return message_0_8.getContent(offsetInMessage, size); - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isInMemory() - { - return true; - } - - @Override - public boolean flowToDisk() - { - return false; - } - }; - } - - private MessageMetaData_0_10 convertMetaData(AMQMessage message_0_8) - { - DeliveryProperties deliveryProps = new DeliveryProperties(); - MessageProperties messageProps = new MessageProperties(); - - int size = (int) message_0_8.getSize(); - ByteBuffer body = ByteBuffer.allocate(size); - message_0_8.getContent(body, 0); - body.flip(); - - BasicContentHeaderProperties properties = - 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.setRoutingKey(message_0_8.getInitialRoutingAddress()); - 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()); - } - - if(properties.getReplyTo() != null && properties.getReplyTo().length() != 0) - { - String origReplyToString = properties.getReplyTo().asString(); - ReplyTo replyTo = new ReplyTo(); - // if the string looks like a binding URL, then attempt to parse it... - try - { - AMQBindingURL burl = new AMQBindingURL(origReplyToString); - AMQShortString routingKey = burl.getRoutingKey(); - if(routingKey != null) - { - replyTo.setRoutingKey(routingKey.asString()); - } - - AMQShortString exchangeName = burl.getExchangeName(); - if(exchangeName != null) - { - replyTo.setExchange(exchangeName.asString()); - } - } - catch (URISyntaxException e) - { - replyTo.setRoutingKey(origReplyToString); - } - messageProps.setReplyTo(replyTo); - - } - - if(properties.getMessageId() != null) - { - try - { - String messageIdAsString = properties.getMessageIdAsString(); - if(messageIdAsString.startsWith("ID:")) - { - messageIdAsString = messageIdAsString.substring(3); - } - UUID uuid = UUID.fromString(messageIdAsString); - messageProps.setMessageId(uuid); - } - catch(IllegalArgumentException e) - { - // ignore - can't parse - } - } - - - - if(properties.getUserId() != null) - { - messageProps.setUserId(properties.getUserId().getBytes()); - } - - FieldTable fieldTable = properties.getHeaders(); - - Map appHeaders = FieldTable.convertToMap(fieldTable); - - if(properties.getType() != null) - { - appHeaders.put("x-jms-type", properties.getTypeAsString()); - } - - - messageProps.setApplicationHeaders(appHeaders); - - Header header = new Header(deliveryProps, messageProps, null); - - - return new MessageMetaData_0_10(header, size, message_0_8.getArrivalTime()); - } - - @Override - public String getType() - { - return "v0-8 to v0-10"; - } -} diff --git a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-1-0/pom.xml b/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-1-0/pom.xml deleted file mode 100644 index 659d3d3cf5..0000000000 --- a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-1-0/pom.xml +++ /dev/null @@ -1,75 +0,0 @@ - - - - 4.0.0 - - - org.apache.qpid - qpid-java-build - 0.32-SNAPSHOT - ../../pom.xml - - - qpid-broker-plugins-amqp-msg-conv-0-8-to-1-0 - Qpid AMQP 0-8 to 1-0 Message Conversion Broker Plug-in - AMQP message conversion (0-8, 0-9 and 0-9-1 to 1-0) broker plug-in - - - - org.apache.qpid - qpid-broker-core - ${project.version} - provided - - - - org.apache.qpid - qpid-broker-codegen - ${project.version} - true - - - - org.apache.qpid - qpid-common - ${project.version} - - - - org.apache.qpid - qpid-broker-plugins-amqp-0-8-protocol - ${project.version} - - - - org.apache.qpid - qpid-amqp-1-0-common - ${project.version} - - - - org.apache.qpid - qpid-broker-plugins-amqp-1-0-protocol - ${project.version} - - - - - - - diff --git a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_0_8_to_1_0.java b/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_0_8_to_1_0.java deleted file mode 100644 index 553b1ba662..0000000000 --- a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_0_8_to_1_0.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.protocol.converter.v0_8_v1_0; - -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.apache.qpid.amqp_1_0.messaging.SectionEncoder; -import org.apache.qpid.amqp_1_0.type.Binary; -import org.apache.qpid.amqp_1_0.type.Section; -import org.apache.qpid.amqp_1_0.type.Symbol; -import org.apache.qpid.amqp_1_0.type.UnsignedByte; -import org.apache.qpid.amqp_1_0.type.UnsignedInteger; -import org.apache.qpid.amqp_1_0.type.messaging.ApplicationProperties; -import org.apache.qpid.amqp_1_0.type.messaging.Header; -import org.apache.qpid.amqp_1_0.type.messaging.Properties; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.protocol.v0_8.AMQMessage; -import org.apache.qpid.server.protocol.v1_0.MessageConverter_to_1_0; -import org.apache.qpid.server.protocol.v1_0.MessageMetaData_1_0; -import org.apache.qpid.url.AMQBindingURL; - -@PluggableService -public class MessageConverter_0_8_to_1_0 extends MessageConverter_to_1_0 -{ - @Override - public Class getInputClass() - { - return AMQMessage.class; - } - - protected MessageMetaData_1_0 convertMetaData(final AMQMessage serverMessage, SectionEncoder sectionEncoder) - { - - List
sections = new ArrayList
(3); - - Header header = new Header(); - - header.setDurable(serverMessage.isPersistent()); - - BasicContentHeaderProperties contentHeader = - serverMessage.getContentHeaderBody().getProperties(); - - header.setPriority(UnsignedByte.valueOf(contentHeader.getPriority())); - final long expiration = serverMessage.getExpiration(); - final long arrivalTime = serverMessage.getArrivalTime(); - - if(expiration > arrivalTime) - { - header.setTtl(UnsignedInteger.valueOf(expiration - arrivalTime)); - } - sections.add(header); - - - Properties props = new Properties(); - - /* - TODO: The following properties are not currently set: - - creationTime - groupId - groupSequence - replyToGroupId - to - */ - - props.setContentEncoding(Symbol.valueOf(contentHeader.getEncodingAsString())); - - props.setContentType(Symbol.valueOf(contentHeader.getContentTypeAsString())); - - // Modify the content type when we are dealing with java object messages produced by the Qpid 0.x client - if(props.getContentType() == Symbol.valueOf("application/java-object-stream")) - { - props.setContentType(Symbol.valueOf("application/x-java-serialized-object")); - } - - final AMQShortString correlationId = contentHeader.getCorrelationId(); - if(correlationId != null) - { - props.setCorrelationId(new Binary(correlationId.getBytes())); - } - - final AMQShortString messageId = contentHeader.getMessageId(); - if(messageId != null) - { - props.setMessageId(new Binary(messageId.getBytes())); - } - final String originalReplyTo = String.valueOf(contentHeader.getReplyTo()); - try - { - AMQBindingURL burl = new AMQBindingURL(originalReplyTo); - String replyTo; - - if(burl.getExchangeName() != null && !burl.getExchangeName().equals(AMQShortString.EMPTY_STRING)) - { - replyTo = burl.getExchangeName().asString(); - - if(burl.getRoutingKey() != null) - { - replyTo += "/" + burl.getRoutingKey().asString(); - } - - } - else if(burl.getQueueName() != null && !burl.getQueueName().equals(AMQShortString.EMPTY_STRING)) - { - replyTo = burl.getQueueName().asString(); - } - else if(burl.getRoutingKey() != null) - { - replyTo = burl.getRoutingKey().asString(); - } - else - { - replyTo = originalReplyTo; - } - - props.setReplyTo(replyTo); - } - catch (URISyntaxException e) - { - props.setReplyTo(originalReplyTo); - } - - - - props.setSubject(serverMessage.getInitialRoutingAddress()); - if(contentHeader.getUserId() != null) - { - props.setUserId(new Binary(contentHeader.getUserId().getBytes())); - } - - sections.add(props); - - Map applicationProperties = FieldTable.convertToMap(contentHeader.getHeaders()); - - if(applicationProperties.containsKey("qpid.subject")) - { - props.setSubject(String.valueOf(applicationProperties.get("qpid.subject"))); - applicationProperties = new LinkedHashMap<>(applicationProperties); - applicationProperties.remove("qpid.subject"); - } - sections.add(new ApplicationProperties(applicationProperties)); - - return new MessageMetaData_1_0(sections, sectionEncoder); - } - - @Override - public String getType() - { - return "v0-8 to v1-0"; - } -} diff --git a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_1_0_to_v0_8.java b/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_1_0_to_v0_8.java deleted file mode 100644 index d4529aedb1..0000000000 --- a/qpid/java/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_1_0_to_v0_8.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.protocol.converter.v0_8_v1_0; - -import java.nio.ByteBuffer; -import java.util.LinkedHashMap; -import java.util.Map; - -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.MessagePublishInfo; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.protocol.v0_8.AMQMessage; -import org.apache.qpid.server.protocol.v0_8.MessageMetaData; -import org.apache.qpid.server.protocol.v1_0.MessageConverter_from_1_0; -import org.apache.qpid.server.protocol.v1_0.MessageMetaData_1_0; -import org.apache.qpid.server.protocol.v1_0.Message_1_0; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; - -@PluggableService -public class MessageConverter_1_0_to_v0_8 implements MessageConverter -{ - private static final int BASIC_CLASS_ID = 60; - - - public Class getInputClass() - { - return Message_1_0.class; - } - - @Override - public Class getOutputClass() - { - return AMQMessage.class; - } - - @Override - public AMQMessage convert(Message_1_0 serverMsg, VirtualHostImpl vhost) - { - return new AMQMessage(convertToStoredMessage(serverMsg), null); - } - - private StoredMessage convertToStoredMessage(final Message_1_0 serverMsg) - { - Object bodyObject = MessageConverter_from_1_0.convertBodyToObject(serverMsg); - - - - - final byte[] messageContent = MessageConverter_from_1_0.convertToBody(bodyObject); - final MessageMetaData messageMetaData_0_8 = convertMetaData(serverMsg, - MessageConverter_from_1_0.getBodyMimeType(bodyObject), - messageContent.length); - - return new StoredMessage() - { - @Override - public MessageMetaData getMetaData() - { - return messageMetaData_0_8; - } - - @Override - public long getMessageNumber() - { - return serverMsg.getMessageNumber(); - } - - @Override - public int getContent(int offsetInMessage, ByteBuffer dst) - { - int size = messageContent.length - offsetInMessage; - if(dst.remaining() < size) - { - size = dst.remaining(); - } - ByteBuffer buf = ByteBuffer.wrap(messageContent, offsetInMessage, size); - dst.put(buf); - return size; - } - - @Override - public ByteBuffer getContent(int offsetInMessage, int size) - { - return ByteBuffer.wrap(messageContent, offsetInMessage, size); - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isInMemory() - { - return true; - } - - @Override - public boolean flowToDisk() - { - return false; - } - }; - } - - private MessageMetaData convertMetaData(final Message_1_0 serverMsg, final String bodyMimeType, final int size) - { - - final MessageMetaData_1_0.MessageHeader_1_0 header = serverMsg.getMessageHeader(); - String key = header.getTo(); - if(key == null) - { - key = header.getSubject(); - } - - MessagePublishInfo publishInfo = new MessagePublishInfo(null, false, false, AMQShortString.valueOf(key)); - - - final BasicContentHeaderProperties props = new BasicContentHeaderProperties(); - props.setAppId(serverMsg.getMessageHeader().getAppId()); - props.setContentType(bodyMimeType); - props.setCorrelationId(serverMsg.getMessageHeader().getCorrelationId()); - props.setDeliveryMode(serverMsg.isPersistent() ? BasicContentHeaderProperties.PERSISTENT : BasicContentHeaderProperties.NON_PERSISTENT); - props.setExpiration(serverMsg.getExpiration()); - props.setMessageId(serverMsg.getMessageHeader().getMessageId()); - props.setPriority(serverMsg.getMessageHeader().getPriority()); - props.setReplyTo(serverMsg.getMessageHeader().getReplyTo()); - props.setTimestamp(serverMsg.getMessageHeader().getTimestamp()); - props.setUserId(serverMsg.getMessageHeader().getUserId()); - - Map headerProps = new LinkedHashMap(); - - if(header.getSubject() != null) - { - headerProps.put("qpid.subject", header.getSubject()); - } - - for(String headerName : serverMsg.getMessageHeader().getHeaderNames()) - { - headerProps.put(headerName, MessageConverter_from_1_0.convertValue(serverMsg.getMessageHeader().getHeader(headerName))); - } - - props.setHeaders(FieldTable.convertToFieldTable(headerProps)); - - final ContentHeaderBody chb = new ContentHeaderBody(props); - chb.setBodySize(size); - - return new MessageMetaData(publishInfo, chb, serverMsg.getArrivalTime()); - } - - - @Override - public String getType() - { - return "v1-0 to v0-8"; - } - - -} diff --git a/qpid/java/broker-plugins/derby-store/pom.xml b/qpid/java/broker-plugins/derby-store/pom.xml deleted file mode 100644 index 1f247c7dcb..0000000000 --- a/qpid/java/broker-plugins/derby-store/pom.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - - 4.0.0 - - - org.apache.qpid - qpid-java-build - 0.32-SNAPSHOT - ../../pom.xml - - - qpid-broker-plugins-derby-store - Qpid Derby Message Store - Apache Derby DB message store broker plug-in - - - - org.apache.qpid - qpid-broker-core - ${project.version} - - - - org.apache.qpid - qpid-broker-codegen - ${project.version} - true - - - - org.apache.derby - derby - ${derby-version} - - - - log4j - log4j - ${log4j-version} - - - - - org.apache.qpid - qpid-test-utils - ${project.version} - test - - - - org.apache.qpid - qpid-broker-core - ${project.version} - test-jar - test - - - - - - - src/main/resources - - - src/main/java - - resources/ - - - - - - diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/AbstractDerbyMessageStore.java b/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/AbstractDerbyMessageStore.java deleted file mode 100644 index df5eec025b..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/AbstractDerbyMessageStore.java +++ /dev/null @@ -1,331 +0,0 @@ -/* -* -* Licensed to the Apache Software Foundation (ASF) under one -* or more contributor license agreements. See the NOTICE file -* distributed with this work for additional information -* regarding copyright ownership. The ASF licenses this file -* to you under the Apache License, Version 2.0 (the -* "License"); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* 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.derby; - - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.store.*; - -public abstract class AbstractDerbyMessageStore extends AbstractJDBCMessageStore -{ - private final AtomicBoolean _messageStoreOpen = new AtomicBoolean(false); - - private long _persistentSizeLowThreshold; - private long _persistentSizeHighThreshold; - private long _totalStoreSize; - private boolean _limitBusted; - - private ConfiguredObject _parent; - - @Override - public final void openMessageStore(final ConfiguredObject parent) - { - if (_messageStoreOpen.compareAndSet(false, true)) - { - _parent = parent; - initMessageStore(parent); - - DerbyUtils.loadDerbyDriver(); - - doOpen(parent); - - final SizeMonitoringSettings sizeMonitorSettings = (SizeMonitoringSettings) parent; - _persistentSizeHighThreshold = sizeMonitorSettings.getStoreOverfullSize(); - _persistentSizeLowThreshold = sizeMonitorSettings.getStoreUnderfullSize(); - - if (_persistentSizeLowThreshold > _persistentSizeHighThreshold || _persistentSizeLowThreshold < 0l) - { - _persistentSizeLowThreshold = _persistentSizeHighThreshold; - } - - createOrOpenMessageStoreDatabase(); - setInitialSize(); - setMaximumMessageId(); - } - } - - protected abstract void doOpen(final ConfiguredObject parent); - - @Override - public final void upgradeStoreStructure() throws StoreException - { - checkMessageStoreOpen(); - - upgrade(_parent); - } - - @Override - public final void closeMessageStore() - { - if (_messageStoreOpen.compareAndSet(true, false)) - { - try - { - doClose(); - } - finally - { - super.closeMessageStore(); - } - } - } - - protected abstract void doClose(); - - @Override - protected boolean isMessageStoreOpen() - { - return _messageStoreOpen.get(); - } - - @Override - protected void checkMessageStoreOpen() - { - if (!_messageStoreOpen.get()) - { - throw new IllegalStateException("Message store is not open"); - } - } - - @Override - protected String getSqlBlobType() - { - return "blob"; - } - - @Override - protected String getSqlVarBinaryType(int size) - { - return "varchar("+size+") for bit data"; - } - - @Override - protected String getSqlBigIntType() - { - return "bigint"; - } - - @Override - protected byte[] getBlobAsBytes(ResultSet rs, int col) throws SQLException - { - return DerbyUtils.getBlobAsBytes(rs, col); - } - - @Override - protected boolean tableExists(final String tableName, final Connection conn) throws SQLException - { - return DerbyUtils.tableExists(tableName, conn); - } - - @Override - protected void storedSizeChange(final int delta) - { - if(getPersistentSizeHighThreshold() > 0) - { - synchronized(this) - { - // the delta supplied is an approximation of a store size change. we don;t want to check the statistic every - // time, so we do so only when there's been enough change that it is worth looking again. We do this by - // assuming the total size will change by less than twice the amount of the message data change. - long newSize = _totalStoreSize += 3*delta; - - Connection conn = null; - try - { - - if(!_limitBusted && newSize > getPersistentSizeHighThreshold()) - { - conn = newAutoCommitConnection(); - _totalStoreSize = getSizeOnDisk(conn); - if(_totalStoreSize > getPersistentSizeHighThreshold()) - { - _limitBusted = true; - _eventManager.notifyEvent(Event.PERSISTENT_MESSAGE_SIZE_OVERFULL); - } - } - else if(_limitBusted && newSize < getPersistentSizeLowThreshold()) - { - long oldSize = _totalStoreSize; - conn = newAutoCommitConnection(); - _totalStoreSize = getSizeOnDisk(conn); - if(oldSize <= _totalStoreSize) - { - - reduceSizeOnDisk(conn); - - _totalStoreSize = getSizeOnDisk(conn); - } - - if(_totalStoreSize < getPersistentSizeLowThreshold()) - { - _limitBusted = false; - _eventManager.notifyEvent(Event.PERSISTENT_MESSAGE_SIZE_UNDERFULL); - } - - - } - } - catch (SQLException e) - { - JdbcUtils.closeConnection(conn, getLogger()); - throw new StoreException("Exception while processing store size change", e); - } - } - } - } - - private void setInitialSize() - { - Connection conn = null; - try - { - conn = newAutoCommitConnection(); - _totalStoreSize = getSizeOnDisk(conn); - } - catch (SQLException e) - { - getLogger().error("Unable to set initial store size", e); - } - finally - { - JdbcUtils.closeConnection(conn, getLogger()); - } - } - - private long getSizeOnDisk(Connection conn) - { - PreparedStatement stmt = null; - try - { - String sizeQuery = "SELECT SUM(T2.NUMALLOCATEDPAGES * T2.PAGESIZE) TOTALSIZE" + - " FROM " + - " SYS.SYSTABLES systabs," + - " TABLE (SYSCS_DIAG.SPACE_TABLE(systabs.tablename)) AS T2" + - " WHERE systabs.tabletype = 'T'"; - - stmt = conn.prepareStatement(sizeQuery); - - ResultSet rs = null; - long size = 0l; - - try - { - rs = stmt.executeQuery(); - while(rs.next()) - { - size = rs.getLong(1); - } - } - finally - { - if(rs != null) - { - rs.close(); - } - } - - return size; - - } - catch (SQLException e) - { - throw new StoreException("Error establishing on disk size", e); - } - finally - { - JdbcUtils.closePreparedStatement(stmt, getLogger()); - } - } - - private void reduceSizeOnDisk(Connection conn) - { - CallableStatement cs = null; - PreparedStatement stmt = null; - try - { - String tableQuery = - "SELECT S.SCHEMANAME, T.TABLENAME FROM SYS.SYSSCHEMAS S, SYS.SYSTABLES T WHERE S.SCHEMAID = T.SCHEMAID AND T.TABLETYPE='T'"; - stmt = conn.prepareStatement(tableQuery); - ResultSet rs = null; - - List schemas = new ArrayList(); - List tables = new ArrayList(); - - try - { - rs = stmt.executeQuery(); - while(rs.next()) - { - schemas.add(rs.getString(1)); - tables.add(rs.getString(2)); - } - } - finally - { - if(rs != null) - { - rs.close(); - } - } - - - cs = conn.prepareCall - ("CALL SYSCS_UTIL.SYSCS_COMPRESS_TABLE(?, ?, ?)"); - - for(int i = 0; i < schemas.size(); i++) - { - cs.setString(1, schemas.get(i)); - cs.setString(2, tables.get(i)); - cs.setShort(3, (short) 0); - cs.execute(); - } - } - catch (SQLException e) - { - throw new StoreException("Error reducing on disk size", e); - } - finally - { - JdbcUtils.closePreparedStatement(stmt, getLogger()); - JdbcUtils.closePreparedStatement(cs, getLogger()); - } - } - - private long getPersistentSizeLowThreshold() - { - return _persistentSizeLowThreshold; - } - - private long getPersistentSizeHighThreshold() - { - return _persistentSizeHighThreshold; - } - -} diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyConfigurationStore.java b/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyConfigurationStore.java deleted file mode 100644 index d96dc8d224..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyConfigurationStore.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.store.derby; - - -import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.store.AbstractJDBCConfigurationStore; -import org.apache.qpid.server.store.ConfiguredObjectRecord; -import org.apache.qpid.server.store.DurableConfigurationStore; -import org.apache.qpid.server.store.FileBasedSettings; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.MessageStoreProvider; -import org.apache.qpid.server.store.StoreException; -import org.apache.qpid.util.FileUtils; - -/** - * Implementation of a DurableConfigurationStore backed by Apache Derby - * that also provides a MessageStore.A - */ -public class DerbyConfigurationStore extends AbstractJDBCConfigurationStore - implements MessageStoreProvider, DurableConfigurationStore -{ - private static final Logger LOGGER = LoggerFactory.getLogger(DerbyConfigurationStore.class); - - private final AtomicBoolean _configurationStoreOpen = new AtomicBoolean(); - private final ProvidedMessageStore _providedMessageStore = new ProvidedMessageStore(); - - private String _connectionURL; - - private ConfiguredObject _parent; - private final Class _rootClass; - - public DerbyConfigurationStore(final Class rootClass) - { - _rootClass = rootClass; - } - - @Override - public void openConfigurationStore(ConfiguredObject parent, - final boolean overwrite, - final ConfiguredObjectRecord... initialRecords) - throws StoreException - { - if (_configurationStoreOpen.compareAndSet(false, true)) - { - _parent = parent; - DerbyUtils.loadDerbyDriver(); - - _connectionURL = DerbyUtils.createConnectionUrl(parent.getName(), ((FileBasedSettings)_parent).getStorePath()); - - createOrOpenConfigurationStoreDatabase(overwrite); - - if(hasNoConfigurationEntries()) - { - update(true, initialRecords); - } - } - } - - @Override - public void upgradeStoreStructure() throws StoreException - { - checkConfigurationStoreOpen(); - upgradeIfNecessary(_parent); - } - - @Override - protected Connection getConnection() throws SQLException - { - checkConfigurationStoreOpen(); - return DriverManager.getConnection(_connectionURL); - } - - @Override - public void closeConfigurationStore() throws StoreException - { - if (_providedMessageStore.isMessageStoreOpen()) - { - throw new IllegalStateException("Cannot close the store as the provided message store is still open"); - } - - if (_configurationStoreOpen.compareAndSet(true, false)) - { - try - { - DerbyUtils.shutdownDatabase(_connectionURL); - } - catch (SQLException e) - { - throw new StoreException("Error closing configuration store", e); - } - } - } - - @Override - protected String getSqlBlobType() - { - return "blob"; - } - - @Override - protected String getSqlVarBinaryType(int size) - { - return "varchar("+size+") for bit data"; - } - - @Override - protected String getSqlBigIntType() - { - return "bigint"; - } - - @Override - protected String getBlobAsString(ResultSet rs, int col) throws SQLException - { - return DerbyUtils.getBlobAsString(rs, col); - } - - @Override - public void onDelete(ConfiguredObject parent) - { - if (_providedMessageStore.isMessageStoreOpen()) - { - throw new IllegalStateException("Cannot delete the store as the provided message store is still open"); - } - - FileBasedSettings fileBasedSettings = (FileBasedSettings) parent; - String storePath = fileBasedSettings.getStorePath(); - - if (!DerbyUtils.MEMORY_STORE_LOCATION.equals(storePath)) - { - if (storePath != null) - { - if (LOGGER.isDebugEnabled()) - { - LOGGER.debug("Deleting store " + storePath); - } - - File configFile = new File(storePath); - if (!FileUtils.delete(configFile, true)) - { - LOGGER.info("Failed to delete the store at location " + storePath); - } - } - } - } - - @Override - public MessageStore getMessageStore() - { - return _providedMessageStore; - } - - @Override - protected boolean tableExists(final String tableName, final Connection conn) throws SQLException - { - return DerbyUtils.tableExists(tableName, conn); - } - - @Override - protected void checkConfigurationStoreOpen() - { - if (!_configurationStoreOpen.get()) - { - throw new IllegalStateException("Configuration store is not open"); - } - } - - @Override - protected Logger getLogger() - { - return LOGGER; - } - - private class ProvidedMessageStore extends AbstractDerbyMessageStore - { - @Override - protected void doOpen(final ConfiguredObject parent) - { - // Nothing to do, store provided by DerbyConfigurationStore - } - - @Override - protected Connection getConnection() throws SQLException - { - checkMessageStoreOpen(); - return DerbyConfigurationStore.this.getConnection(); - } - - @Override - protected void doClose() - { - // Nothing to do, store provided by DerbyConfigurationStore - } - - @Override - public String getStoreLocation() - { - return ((FileBasedSettings)(DerbyConfigurationStore.this._parent)).getStorePath(); - } - - @Override - public File getStoreLocationAsFile() - { - return DerbyUtils.isInMemoryDatabase(getStoreLocation()) ? null : new File(getStoreLocation()); - } - - @Override - protected Logger getLogger() - { - return DerbyConfigurationStore.this.getLogger(); - } - } -} diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyMessageStore.java b/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyMessageStore.java deleted file mode 100644 index 10fed76b60..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyMessageStore.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.store.derby; - - -import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.store.FileBasedSettings; -import org.apache.qpid.server.store.StoreException; -import org.apache.qpid.util.FileUtils; - -/** - * Implementation of a MessageStore backed by Apache Derby. - */ -public class DerbyMessageStore extends AbstractDerbyMessageStore -{ - private static final Logger LOGGER = LoggerFactory.getLogger(DerbyMessageStore.class); - - private String _connectionURL; - private ConfiguredObject _parent; - - @Override - protected void doOpen(final ConfiguredObject parent) - { - _parent = parent; - _connectionURL = DerbyUtils.createConnectionUrl(parent.getName(), ((FileBasedSettings)_parent).getStorePath()); - } - - @Override - protected Connection getConnection() throws SQLException - { - checkMessageStoreOpen(); - return DriverManager.getConnection(_connectionURL); - } - - @Override - protected void doClose() - { - try - { - DerbyUtils.shutdownDatabase(_connectionURL); - } - catch (SQLException e) - { - throw new StoreException("Error closing configuration store", e); - } - } - - @Override - public void onDelete(ConfiguredObject parent) - { - if (isMessageStoreOpen()) - { - throw new IllegalStateException("Cannot delete the store as the provided message store is still open"); - } - - FileBasedSettings fileBasedSettings = (FileBasedSettings)parent; - String storePath = fileBasedSettings.getStorePath(); - - if (storePath != null) - { - if (LOGGER.isDebugEnabled()) - { - LOGGER.debug("Deleting store " + storePath); - } - - File configFile = new File(storePath); - if (!FileUtils.delete(configFile, true)) - { - LOGGER.info("Failed to delete the store at location " + storePath); - } - } - } - - @Override - protected Logger getLogger() - { - return LOGGER; - } - - - @Override - public String getStoreLocation() - { - return ((FileBasedSettings)_parent).getStorePath(); - } - - @Override - public File getStoreLocationAsFile() - { - return DerbyUtils.isInMemoryDatabase(getStoreLocation()) ? null : new File(getStoreLocation()); - } -} diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbySystemConfig.java b/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbySystemConfig.java deleted file mode 100644 index d3a1fa2bbc..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbySystemConfig.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.store.derby; - -import org.apache.qpid.server.model.ManagedAttribute; -import org.apache.qpid.server.model.SystemConfig; -import org.apache.qpid.server.store.FileBasedSettings; -import org.apache.qpid.server.store.SizeMonitoringSettings; - -public interface DerbySystemConfig> extends SystemConfig, FileBasedSettings, - SizeMonitoringSettings -{ - @ManagedAttribute(mandatory = true) - String getStorePath(); - - @ManagedAttribute(mandatory = true, defaultValue = "0") - Long getStoreUnderfullSize(); - - @ManagedAttribute(mandatory = true, defaultValue = "0") - Long getStoreOverfullSize(); -} diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbySystemConfigImpl.java b/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbySystemConfigImpl.java deleted file mode 100644 index 0cc4f2b18c..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbySystemConfigImpl.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.derby; - -import java.util.Map; - -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.LogRecorder; -import org.apache.qpid.server.model.AbstractSystemConfig; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.BrokerShutdownProvider; -import org.apache.qpid.server.model.ManagedAttributeField; -import org.apache.qpid.server.model.ManagedObject; -import org.apache.qpid.server.model.SystemConfigFactoryConstructor; -import org.apache.qpid.server.store.DurableConfigurationStore; - -@ManagedObject(category = false, type = DerbySystemConfigImpl.SYSTEM_CONFIG_TYPE) -public class DerbySystemConfigImpl extends AbstractSystemConfig implements DerbySystemConfig -{ - public static final String SYSTEM_CONFIG_TYPE = "DERBY"; - - @ManagedAttributeField - private String _storePath; - @ManagedAttributeField - private Long _storeUnderfullSize; - @ManagedAttributeField - private Long _storeOverfullSize; - - @SystemConfigFactoryConstructor - public DerbySystemConfigImpl(final TaskExecutor taskExecutor, - final EventLogger eventLogger, - final LogRecorder logRecorder, - final Map attributes, - final BrokerShutdownProvider brokerShutdownProvider) - { - super(taskExecutor, eventLogger, logRecorder, attributes, brokerShutdownProvider); - } - - @Override - protected DurableConfigurationStore createStoreObject() - { - return new DerbyConfigurationStore(Broker.class); - } - - @Override - public String getStorePath() - { - return _storePath; - } - - @Override - public Long getStoreUnderfullSize() - { - return _storeUnderfullSize; - } - - @Override - public Long getStoreOverfullSize() - { - return _storeOverfullSize; - } -} diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyUtils.java b/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyUtils.java deleted file mode 100644 index 8116274261..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyUtils.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.store.derby; - - -import java.io.File; -import java.io.IOException; -import java.io.Writer; -import java.nio.charset.Charset; -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 org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.store.StoreException; - -public class DerbyUtils -{ - public static final String MEMORY_STORE_LOCATION = ":memory:"; - public static final String DERBY_SINGLE_DB_SHUTDOWN_CODE = "08006"; - private static final String SQL_DRIVER_NAME = "org.apache.derby.jdbc.EmbeddedDriver"; - private static final String TABLE_EXISTENCE_QUERY = "SELECT 1 FROM SYS.SYSTABLES WHERE TABLENAME = ?"; - private static final Charset UTF8_CHARSET = Charset.forName("UTF-8"); - - private static final Logger DERBY_LOG = LoggerFactory.getLogger("DERBY"); - public static final DerbyLogWriter DERBY_LOG_WRITER = new DerbyLogWriter(); - public static final String DERBY_STREAM_ERROR_METHOD = "derby.stream.error.method"; - - public static void loadDerbyDriver() - { - try - { - // set the error log output - System.setProperty(DERBY_STREAM_ERROR_METHOD, - "org.apache.qpid.server.store.derby.DerbyUtils.getDerbyLogWriter"); - - Class driverClass = (Class) Class.forName(SQL_DRIVER_NAME); - } - catch (ClassNotFoundException e) - { - throw new StoreException("Failed to load driver " + SQL_DRIVER_NAME, e); - } - } - - public static Writer getDerbyLogWriter() - { - return DERBY_LOG_WRITER; - } - - public static String createConnectionUrl(final String name, final String databasePath) - { - // Derby wont use an existing directory, so we append parent name - if (isInMemoryDatabase(databasePath)) - { - return "jdbc:derby:" + MEMORY_STORE_LOCATION + "/" + name + ";create=true"; - } - else - { - 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."); - } - } - return "jdbc:derby:" + databasePath + "/" + name + ";create=true"; - } - - } - - public static boolean isInMemoryDatabase(final String databasePath) - { - return MEMORY_STORE_LOCATION.equals(databasePath); - } - - public static void shutdownDatabase(String connectionURL) throws SQLException - { - try - { - Connection conn = DriverManager.getConnection(connectionURL + ";shutdown=true"); - // Shouldn't reach this point - shutdown=true should throw SQLException - conn.close(); - } - catch (SQLException e) - { - if (e.getSQLState().equalsIgnoreCase(DerbyUtils.DERBY_SINGLE_DB_SHUTDOWN_CODE)) - { - //expected and represents a clean shutdown of this database only, do nothing. - } - else - { - throw e; - } - } - } - - public static String getBlobAsString(ResultSet rs, int col) throws SQLException - { - Blob blob = rs.getBlob(col); - if(blob == null) - { - return null; - } - byte[] bytes = blob.getBytes(1, (int) blob.length()); - return new String(bytes, UTF8_CHARSET); - } - - protected static byte[] getBlobAsBytes(ResultSet rs, int col) throws SQLException - { - Blob dataAsBlob = rs.getBlob(col); - return dataAsBlob.getBytes(1,(int) dataAsBlob.length()); - } - - public static boolean tableExists(final String tableName, final Connection conn) throws SQLException - { - PreparedStatement stmt = conn.prepareStatement(TABLE_EXISTENCE_QUERY); - try - { - stmt.setString(1, tableName); - ResultSet rs = stmt.executeQuery(); - try - { - return rs.next(); - } - finally - { - rs.close(); - } - } - finally - { - stmt.close(); - } - } - - - private static class DerbyLogWriter extends Writer - { - - public static final String DERBY_STARTUP_MESSAGE = "Booting Derby version "; - public static final String DERBY_SHUTDOWN_MESSAGE = "Shutting down instance "; - public static final String DERBY_CLASS_LOADER_STARTED_MESSAGE = "Database Class Loader started"; - public static final String DERBY_SYSTEM_HOME = "derby.system.home"; - public static final String DASHED_LINE = "\\s*-*\\s*"; - - private final ThreadLocal _threadLocalBuffer = new ThreadLocal() - { - @Override - protected StringBuilder initialValue() - { - return new StringBuilder(); - } - }; - - @Override - public void write(final char[] cbuf, final int off, final int len) throws IOException - { - _threadLocalBuffer.get().append(cbuf, off, len); - } - - @Override - public void flush() throws IOException - { - String logMessage = _threadLocalBuffer.get().toString(); - if(!logMessage.matches(DASHED_LINE)) - { - if(logMessage.contains(DERBY_STARTUP_MESSAGE)) - { - // the first line of the message containing the startup message is the current date/time, which - // we can remove - logMessage = logMessage.substring(logMessage.indexOf('\n') + 1); - } - - // This is pretty hideous, but since the Derby logging doesn't have any way of informing us of priority - // we simply have to assume everything is a warning except known startup / shutdown messages - // which we match using known prefixes. - - if(logMessage.startsWith(DERBY_STARTUP_MESSAGE) - || logMessage.startsWith(DERBY_SHUTDOWN_MESSAGE)) - { - DERBY_LOG.info(logMessage); - } - else if(logMessage.startsWith(DERBY_SYSTEM_HOME) - || logMessage.startsWith(DERBY_STREAM_ERROR_METHOD) - || logMessage.startsWith("java.vendor") - || logMessage.startsWith(DERBY_CLASS_LOADER_STARTED_MESSAGE)) - { - DERBY_LOG.debug(logMessage); - } - else - { - DERBY_LOG.warn(logMessage); - } - - } - _threadLocalBuffer.set(new StringBuilder()); - } - - @Override - public void close() throws IOException - { - - } - } -} - diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhost/derby/DerbyVirtualHost.java b/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhost/derby/DerbyVirtualHost.java deleted file mode 100644 index 4935d5e707..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhost/derby/DerbyVirtualHost.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.virtualhost.derby; - -import org.apache.qpid.server.exchange.ExchangeImpl; -import org.apache.qpid.server.model.ManagedAttribute; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.store.SizeMonitoringSettings; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; - -public interface DerbyVirtualHost> extends VirtualHostImpl,ExchangeImpl>, org.apache.qpid.server.store.FileBasedSettings, SizeMonitoringSettings -{ - String STORE_PATH = "storePath"; - - @ManagedAttribute(mandatory = true, defaultValue = "${qpid.work_dir}${file.separator}${this:name}${file.separator}messages") - String getStorePath(); - - @ManagedAttribute(mandatory = true, defaultValue = "0") - Long getStoreUnderfullSize(); - - @ManagedAttribute(mandatory = true, defaultValue = "0") - Long getStoreOverfullSize(); -} diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhost/derby/DerbyVirtualHostImpl.java b/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhost/derby/DerbyVirtualHostImpl.java deleted file mode 100644 index dbaf5e55b7..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhost/derby/DerbyVirtualHostImpl.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.virtualhost.derby; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.ManagedAttributeField; -import org.apache.qpid.server.model.ManagedObject; -import org.apache.qpid.server.model.ManagedObjectFactoryConstructor; -import org.apache.qpid.server.model.VirtualHostNode; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.derby.DerbyMessageStore; -import org.apache.qpid.server.util.FileHelper; -import org.apache.qpid.server.virtualhost.AbstractVirtualHost; - -import java.util.Map; - -@ManagedObject(category = false, type = DerbyVirtualHostImpl.VIRTUAL_HOST_TYPE) -public class DerbyVirtualHostImpl extends AbstractVirtualHost implements DerbyVirtualHost -{ - public static final String VIRTUAL_HOST_TYPE = "DERBY"; - - @ManagedAttributeField - private String _storePath; - - @ManagedAttributeField - private Long _storeUnderfullSize; - - @ManagedAttributeField - private Long _storeOverfullSize; - - @ManagedObjectFactoryConstructor - public DerbyVirtualHostImpl(final Map attributes, - final VirtualHostNode virtualHostNode) - { - super(attributes, virtualHostNode); - } - - - @Override - protected MessageStore createMessageStore() - { - return new DerbyMessageStore(); - } - - @Override - public String getStorePath() - { - return _storePath; - } - - @Override - public Long getStoreUnderfullSize() - { - return _storeUnderfullSize; - } - - @Override - public Long getStoreOverfullSize() - { - return _storeOverfullSize; - } - - @Override - protected void validateMessageStoreCreation() - { - if (!new FileHelper().isWritableDirectory(getStorePath())) - { - throw new IllegalConfigurationException("The store path is not writable directory"); - } - } -} diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNode.java b/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNode.java deleted file mode 100644 index 81a9167924..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNode.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.virtualhostnode.derby; - - -import org.apache.qpid.server.model.ManagedAttribute; - -public interface DerbyVirtualHostNode> extends org.apache.qpid.server.model.VirtualHostNode, org.apache.qpid.server.store.FileBasedSettings -{ - String STORE_PATH = "storePath"; - - @ManagedAttribute(mandatory = true, defaultValue = "${qpid.work_dir}${file.separator}${this:name}${file.separator}config") - String getStorePath(); -} diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNodeImpl.java b/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNodeImpl.java deleted file mode 100644 index 8224a22929..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNodeImpl.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.virtualhostnode.derby; - -import java.util.Collection; -import java.util.Collections; -import java.util.Map; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.logging.messages.ConfigStoreMessages; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ManagedAttributeField; -import org.apache.qpid.server.model.ManagedObject; -import org.apache.qpid.server.model.ManagedObjectFactoryConstructor; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.store.DurableConfigurationStore; -import org.apache.qpid.server.store.derby.DerbyConfigurationStore; -import org.apache.qpid.server.util.FileHelper; -import org.apache.qpid.server.virtualhostnode.AbstractStandardVirtualHostNode; - -@ManagedObject( category = false, - type = DerbyVirtualHostNodeImpl.VIRTUAL_HOST_NODE_TYPE, - validChildTypes = "org.apache.qpid.server.virtualhostnode.derby.DerbyVirtualHostNodeImpl#getSupportedChildTypes()" ) -public class DerbyVirtualHostNodeImpl extends AbstractStandardVirtualHostNode implements DerbyVirtualHostNode -{ - public static final String VIRTUAL_HOST_NODE_TYPE = "DERBY"; - - @ManagedAttributeField - private String _storePath; - - @ManagedObjectFactoryConstructor - public DerbyVirtualHostNodeImpl(Map attributes, Broker parent) - { - super(attributes, parent); - } - - @Override - protected void writeLocationEventLog() - { - getEventLogger().message(getConfigurationStoreLogSubject(), ConfigStoreMessages.STORE_LOCATION(getStorePath())); - } - - @Override - protected DurableConfigurationStore createConfigurationStore() - { - return new DerbyConfigurationStore(VirtualHost.class); - } - - @Override - public String getStorePath() - { - return _storePath; - } - - @Override - public String toString() - { - return getClass().getSimpleName() + " [id=" + getId() + ", name=" + getName() + ", storePath=" + getStorePath() + "]"; - } - - - public static Map> getSupportedChildTypes() - { - return Collections.singletonMap(VirtualHost.class.getSimpleName(), getSupportedVirtualHostTypes(true)); - } - - @Override - public void validateOnCreate() - { - if (!new FileHelper().isWritableDirectory(getStorePath())) - { - throw new IllegalConfigurationException("The store path is not writable directory"); - } - } -} diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhost/derby/add.js b/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhost/derby/add.js deleted file mode 100644 index 323b8e9750..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhost/derby/add.js +++ /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. - */ - -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/dom", - "dojo/dom-construct", - "dojo/json", - "dijit/registry", - "dojo/text!virtualhost/sizemonitoring/add.html", - "qpid/common/util", - "dijit/form/ValidationTextBox", - "dijit/form/NumberTextBox", - "dojo/domReady!"], - function (xhr, parser, dom, domConstruct, json, registry, template, util) - { - return { - show: function (data) - { - this.containerNode = domConstruct.create("div", {innerHTML: template}, data.containerNode); - parser.parse(this.containerNode).then(function(instances) - { - registry.byId("addVirtualHost.storeUnderfullSize").set("regExpGen", util.numericOrContextVarRegexp); - registry.byId("addVirtualHost.storeOverfullSize").set("regExpGen", util.numericOrContextVarRegexp); - }); - } - }; - } -); diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhost/derby/edit.js b/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhost/derby/edit.js deleted file mode 100644 index c1018313b8..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhost/derby/edit.js +++ /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. - */ -define(["qpid/common/util", "dijit/registry", "dojo/domReady!"], - function (util, registry) - { - return { - show: function(data) - { - util.parseHtmlIntoDiv(data.containerNode, "virtualhost/sizemonitoring/edit.html", - function() - { - registry.byId("editVirtualHost.storeUnderfullSize").set("regExpGen", util.numericOrContextVarRegexp); - registry.byId("editVirtualHost.storeOverfullSize").set("regExpGen", util.numericOrContextVarRegexp); - }); - } - }; - } -); diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhost/derby/show.js b/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhost/derby/show.js deleted file mode 100644 index e53ad75fe4..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhost/derby/show.js +++ /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. - */ - -define(["qpid/common/util", - "dojo/domReady!"], - function (util) - { - var fields = ["storePath", "storeUnderfullSize", "storeOverfullSize"]; - - function Derby(data) - { - util.buildUI(data.containerNode, data.parent, "virtualhost/sizemonitoring/show.html", fields, this); - } - - Derby.prototype.update = function(data) - { - util.updateUI(data, fields, this); - } - - return Derby; - } -); diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhostnode/derby/add.js b/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhostnode/derby/add.js deleted file mode 100644 index d981f1e13f..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhostnode/derby/add.js +++ /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. - * - */ -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/dom", - "dojo/dom-construct", - "dojo/json", - "dijit/registry", - "dojo/text!virtualhostnode/derby/add.html", - "dijit/form/ValidationTextBox", - "dijit/form/CheckBox", - "dojo/domReady!"], - function (xhr, parser, dom, domConstruct, json, registry, template) - { - return { - show: function (data) - { - this.containerNode = domConstruct.create("div", {innerHTML: template}, data.containerNode); - parser.parse(this.containerNode); - } - }; - } -); diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhostnode/derby/edit.js b/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhostnode/derby/edit.js deleted file mode 100644 index a7f5d05719..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhostnode/derby/edit.js +++ /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. - */ -define(["qpid/common/util", "dijit/registry", "dojo/domReady!"], - function (util, registry) - { - return { - show: function(data) - { - util.parseHtmlIntoDiv(data.containerNode, "virtualhostnode/filebased/edit.html", - function() - { - registry.byId("editVirtualHostNode.storePath").set("disabled", data.data.state != "STOPPED"); - }); - } - }; - } -); diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhostnode/derby/show.js b/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhostnode/derby/show.js deleted file mode 100644 index ffbe4bfacd..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/resources/js/qpid/management/virtualhostnode/derby/show.js +++ /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. - * - */ -define(["qpid/common/util", "dojo/domReady!"], - function (util) - { - var fields = ["storePath"]; - - function DerbyNode(data) - { - this.parent = data.parent; - util.buildUI(data.containerNode, data.parent, "virtualhostnode/derby/show.html", fields, this); - } - - DerbyNode.prototype.update=function(data) - { - util.updateUI(data, fields, this); - }; - - return DerbyNode; -}); diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/resources/virtualhostnode/derby/add.html b/qpid/java/broker-plugins/derby-store/src/main/java/resources/virtualhostnode/derby/add.html deleted file mode 100644 index 4e82ab09e9..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/resources/virtualhostnode/derby/add.html +++ /dev/null @@ -1,35 +0,0 @@ - -
-
-
Store path:
-
- -
-
-
-
diff --git a/qpid/java/broker-plugins/derby-store/src/main/java/resources/virtualhostnode/derby/show.html b/qpid/java/broker-plugins/derby-store/src/main/java/resources/virtualhostnode/derby/show.html deleted file mode 100644 index d86d9cfa03..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/main/java/resources/virtualhostnode/derby/show.html +++ /dev/null @@ -1,21 +0,0 @@ - - -
-
Configuration store path:
-
-
diff --git a/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreConfigurationTest.java b/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreConfigurationTest.java deleted file mode 100644 index 4a71fe2faf..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreConfigurationTest.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.store.derby; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.apache.qpid.server.model.ConfiguredObjectFactory; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.model.VirtualHostNode; -import org.apache.qpid.server.store.AbstractDurableConfigurationStoreTestCase; -import org.apache.qpid.server.virtualhostnode.derby.DerbyVirtualHostNode; - -public class DerbyMessageStoreConfigurationTest extends AbstractDurableConfigurationStoreTestCase -{ - - @Override - protected VirtualHostNode createVirtualHostNode(String storeLocation, ConfiguredObjectFactory factory) - { - final DerbyVirtualHostNode parent = mock(DerbyVirtualHostNode.class); - when(parent.getStorePath()).thenReturn(storeLocation); - return parent; - } - - @Override - protected DerbyConfigurationStore createConfigStore() throws Exception - { - return new DerbyConfigurationStore(VirtualHost.class); - } - -} diff --git a/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreQuotaEventsTest.java b/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreQuotaEventsTest.java deleted file mode 100644 index 0aeb6bd0e8..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreQuotaEventsTest.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.store.derby; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.Collections; -import java.util.Map; - -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.MessageStoreQuotaEventsTestBase; -import org.apache.qpid.server.virtualhost.derby.DerbyVirtualHost; - -public class DerbyMessageStoreQuotaEventsTest extends MessageStoreQuotaEventsTestBase -{ - private static final int NUMBER_OF_MESSAGES_TO_OVERFILL_STORE = 10; - - /** - * Estimated using an assumption that a physical disk space occupied by a - * message is 3 times bigger then a message size - */ - private static final long OVERFULL_SIZE = (long) (MESSAGE_DATA.length * 3 * NUMBER_OF_MESSAGES_TO_OVERFILL_STORE * 0.8); - - private static final long UNDERFULL_SIZE = (long) (OVERFULL_SIZE * 0.8); - - @Override - protected int getNumberOfMessagesToFillStore() - { - return NUMBER_OF_MESSAGES_TO_OVERFILL_STORE; - } - - @Override - protected VirtualHost createVirtualHost(String storeLocation) - { - final DerbyVirtualHost parent = mock(DerbyVirtualHost.class); - when(parent.getContext()).thenReturn(createContextSettings()); - when(parent.getContextKeys(false)).thenReturn(Collections.emptySet()); - when(parent.getStorePath()).thenReturn(storeLocation); - when(parent.getStoreOverfullSize()).thenReturn(OVERFULL_SIZE); - when(parent.getStoreUnderfullSize()).thenReturn(UNDERFULL_SIZE); - return parent; - } - - @Override - protected MessageStore createStore() throws Exception - { - return new DerbyMessageStore(); - } - - private Map createContextSettings() - { - return Collections.emptyMap(); - } - - -} diff --git a/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreTest.java b/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreTest.java deleted file mode 100644 index 0b1847bb59..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreTest.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.store.derby; - - -import java.io.File; - -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.MessageStoreTestCase; -import org.apache.qpid.server.virtualhost.derby.DerbyVirtualHost; -import org.apache.qpid.util.FileUtils; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class DerbyMessageStoreTest extends MessageStoreTestCase -{ - private String _storeLocation; - - @Override - public void tearDown() throws Exception - { - try - { - deleteStoreIfExists(); - } - finally - { - super.tearDown(); - } - } - - public void testOnDelete() throws Exception - { - File location = new File(_storeLocation); - assertTrue("Store does not exist at " + _storeLocation, location.exists()); - - getStore().closeMessageStore(); - assertTrue("Store does not exist at " + _storeLocation, location.exists()); - - DerbyVirtualHost mockVH = mock(DerbyVirtualHost.class); - when(mockVH.getStorePath()).thenReturn(_storeLocation); - - getStore().onDelete(mockVH); - assertFalse("Store exists at " + _storeLocation, location.exists()); - } - - @Override - protected VirtualHost createVirtualHost() - { - _storeLocation = TMP_FOLDER + File.separator + getTestName(); - deleteStoreIfExists(); - - final DerbyVirtualHost parent = mock(DerbyVirtualHost.class); - when(parent.getStorePath()).thenReturn(_storeLocation); - return parent; - } - - private void deleteStoreIfExists() - { - if (_storeLocation != null) - { - File location = new File(_storeLocation); - if (location.exists()) - { - FileUtils.delete(location, true); - } - } - } - - @Override - protected MessageStore createMessageStore() - { - return new DerbyMessageStore(); - } - -} diff --git a/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNodeTest.java b/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNodeTest.java deleted file mode 100644 index 5afbc7aceb..0000000000 --- a/qpid/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNodeTest.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.virtualhostnode.derby; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.nio.file.Files; -import java.nio.file.attribute.PosixFileAttributeView; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.configuration.updater.TaskExecutorImpl; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.BrokerModel; -import org.apache.qpid.server.model.ConfiguredObjectFactoryImpl; -import org.apache.qpid.server.model.SystemConfig; -import org.apache.qpid.server.model.VirtualHostNode; -import org.apache.qpid.server.model.adapter.BrokerAdapter; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.test.utils.TestFileUtils; - -public class DerbyVirtualHostNodeTest extends QpidTestCase -{ - private TaskExecutor _taskExecutor; - private File _workDir; - private Broker _broker; - - @Override - public void setUp() throws Exception - { - super.setUp(); - _taskExecutor = new TaskExecutorImpl(); - _taskExecutor.start(); - _workDir = TestFileUtils.createTestDirectory("qpid.work_dir", true); - setTestSystemProperty("qpid.work_dir", _workDir.getAbsolutePath()); - _broker = createBroker(); - } - - public void tearDown() throws Exception - { - try - { - _broker.close(); - } - finally - { - _taskExecutor.stop(); - TestFileUtils.delete(_workDir, true); - super.tearDown(); - } - } - - public void testCreateAndCloseVirtualHostNode() throws Exception - { - String nodeName = getTestName(); - Map nodeData = new HashMap<>(); - nodeData.put(VirtualHostNode.NAME, nodeName); - nodeData.put(VirtualHostNode.TYPE, DerbyVirtualHostNodeImpl.VIRTUAL_HOST_NODE_TYPE); - - VirtualHostNode virtualHostNode = (VirtualHostNode)_broker.createChild(VirtualHostNode.class, nodeData); - virtualHostNode.start(); - virtualHostNode.close(); - } - - - public void testCreateDuplicateVirtualHostNodeAndClose() throws Exception - { - - String nodeName = getTestName(); - Map nodeData = new HashMap<>(); - nodeData.put(VirtualHostNode.NAME, nodeName); - nodeData.put(VirtualHostNode.TYPE, DerbyVirtualHostNodeImpl.VIRTUAL_HOST_NODE_TYPE); - - VirtualHostNode virtualHostNode = (VirtualHostNode)_broker.createChild(VirtualHostNode.class, nodeData); - virtualHostNode.start(); - - try - { - _broker.createChild(VirtualHostNode.class, nodeData); - } - catch(Exception e) - { - assertEquals("Unexpected message", "Child of type " + virtualHostNode.getClass().getSimpleName() + " already exists with name of " + getTestName(), e.getMessage()); - } - virtualHostNode.close(); - } - - public void testOnCreateValidationForFileStorePath() throws Exception - { - File file = new File(_workDir, getTestName()); - file.createNewFile(); - - String nodeName = getTestName(); - Map nodeData = new HashMap<>(); - nodeData.put(VirtualHostNode.NAME, nodeName); - nodeData.put(VirtualHostNode.TYPE, DerbyVirtualHostNodeImpl.VIRTUAL_HOST_NODE_TYPE); - nodeData.put(DerbyVirtualHostNodeImpl.STORE_PATH, file.getAbsolutePath()); - try - { - _broker.createChild(VirtualHostNode.class, nodeData); - fail("Cannot create store for the file store path"); - } - catch(IllegalConfigurationException e) - { - // pass - } - - } - - - public void testOnCreateValidationForNonWritableStorePath() throws Exception - { - if (Files.getFileStore(_workDir.toPath()).supportsFileAttributeView(PosixFileAttributeView.class)) - { - File file = new File(_workDir, getTestName()); - file.mkdirs(); - if (file.setWritable(false, false)) - { - String nodeName = getTestName(); - Map nodeData = new HashMap<>(); - nodeData.put(VirtualHostNode.NAME, nodeName); - nodeData.put(VirtualHostNode.TYPE, DerbyVirtualHostNodeImpl.VIRTUAL_HOST_NODE_TYPE); - nodeData.put(DerbyVirtualHostNodeImpl.STORE_PATH, file.getAbsolutePath()); - try - { - _broker.createChild(VirtualHostNode.class, nodeData); - fail("Cannot create store for the non writable store path"); - } - catch (IllegalConfigurationException e) - { - // pass - } - } - } - } - - private BrokerAdapter createBroker() - { - Map brokerAttributes = Collections.singletonMap(Broker.NAME, "Broker"); - SystemConfig parent = mock(SystemConfig.class); - when(parent.getEventLogger()).thenReturn(new EventLogger()); - when(parent.getCategoryClass()).thenReturn(SystemConfig.class); - when(parent.getTaskExecutor()).thenReturn(_taskExecutor); - when(parent.getChildExecutor()).thenReturn(_taskExecutor); - when(parent.getModel()).thenReturn(BrokerModel.getInstance()); - when(parent.getObjectFactory()).thenReturn(new ConfiguredObjectFactoryImpl(BrokerModel.getInstance())); - BrokerAdapter broker = new BrokerAdapter(brokerAttributes, parent); - broker.start(); - return broker; - } -} diff --git a/qpid/java/broker-plugins/jdbc-provider-bone/pom.xml b/qpid/java/broker-plugins/jdbc-provider-bone/pom.xml deleted file mode 100644 index 2f742459f0..0000000000 --- a/qpid/java/broker-plugins/jdbc-provider-bone/pom.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - 4.0.0 - - - org.apache.qpid - qpid-java-build - 0.32-SNAPSHOT - ../../pom.xml - - - qpid-broker-plugins-jdbc-provider-bone - Qpid JDBC Message Store Connection Pooling Plug-in - JDBC Message Store Connection Pooling broker plug-in using BoneCP - - - - org.apache.qpid - qpid-broker-core - ${project.version} - provided - - - - org.apache.qpid - qpid-broker-codegen - ${project.version} - true - - - - com.jolbox - bonecp - ${bonecp-version} - - - - com.google.guava - guava - - - - - - com.google.guava - guava - ${guava-version} - runtime - - - - - - - - src/main/resources - - - src/main/java - - resources/ - - - - - - diff --git a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/org/apache/qpid/server/store/jdbc/bonecp/BoneCPConnectionProvider.java b/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/org/apache/qpid/server/store/jdbc/bonecp/BoneCPConnectionProvider.java deleted file mode 100644 index 2687a32bf9..0000000000 --- a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/org/apache/qpid/server/store/jdbc/bonecp/BoneCPConnectionProvider.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.store.jdbc.bonecp; - -import static org.apache.qpid.server.store.jdbc.bonecp.BoneCPConnectionProviderFactory.MAX_CONNECTIONS_PER_PARTITION; -import static org.apache.qpid.server.store.jdbc.bonecp.BoneCPConnectionProviderFactory.MIN_CONNECTIONS_PER_PARTITION; -import static org.apache.qpid.server.store.jdbc.bonecp.BoneCPConnectionProviderFactory.PARTITION_COUNT; - -import com.jolbox.bonecp.BoneCP; -import com.jolbox.bonecp.BoneCPConfig; -import org.apache.qpid.server.store.jdbc.ConnectionProvider; - -import java.sql.Connection; -import java.sql.SQLException; -import java.util.Map; - -public class BoneCPConnectionProvider implements ConnectionProvider -{ - public static final int DEFAULT_MIN_CONNECTIONS_PER_PARTITION = 5; - public static final int DEFAULT_MAX_CONNECTIONS_PER_PARTITION = 10; - public static final int DEFAULT_PARTITION_COUNT = 4; - - private final BoneCP _connectionPool; - - public BoneCPConnectionProvider(String connectionUrl, String username, String password, Map providerAttributes) throws SQLException - { - BoneCPConfig config = new BoneCPConfig(); - config.setJdbcUrl(connectionUrl); - if (username != null) - { - config.setUsername(username); - config.setPassword(password); - } - - config.setMinConnectionsPerPartition(convertToIntWithDefault(MIN_CONNECTIONS_PER_PARTITION, providerAttributes, DEFAULT_MIN_CONNECTIONS_PER_PARTITION)); - config.setMaxConnectionsPerPartition(convertToIntWithDefault(MAX_CONNECTIONS_PER_PARTITION, providerAttributes, DEFAULT_MAX_CONNECTIONS_PER_PARTITION)); - config.setPartitionCount(convertToIntWithDefault(PARTITION_COUNT, providerAttributes, DEFAULT_PARTITION_COUNT)); - - _connectionPool = new BoneCP(config); - } - - private int convertToIntWithDefault(String key, Map context, int defaultValue) - { - if (context.containsKey(key)) - { - try - { - return Integer.parseInt(context.get(key)); - } - catch (NumberFormatException e) - { - return defaultValue; - } - } - else - { - return defaultValue; - } - } - @Override - public Connection getConnection() throws SQLException - { - return _connectionPool.getConnection(); - } - - @Override - public void close() throws SQLException - { - _connectionPool.shutdown(); - } -} diff --git a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/org/apache/qpid/server/store/jdbc/bonecp/BoneCPConnectionProviderFactory.java b/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/org/apache/qpid/server/store/jdbc/bonecp/BoneCPConnectionProviderFactory.java deleted file mode 100644 index f894a6a27a..0000000000 --- a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/org/apache/qpid/server/store/jdbc/bonecp/BoneCPConnectionProviderFactory.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.store.jdbc.bonecp; - -import static java.util.Arrays.asList; -import static java.util.Collections.unmodifiableSet; - -import org.apache.qpid.server.plugin.JDBCConnectionProviderFactory; -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.store.jdbc.ConnectionProvider; - -import java.sql.SQLException; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -@PluggableService -public class BoneCPConnectionProviderFactory implements JDBCConnectionProviderFactory -{ - public static final String PARTITION_COUNT = "qpid.jdbcstore.bonecp.partitionCount"; - public static final String MAX_CONNECTIONS_PER_PARTITION = "qpid.jdbcstore.bonecp.maxConnectionsPerPartition"; - public static final String MIN_CONNECTIONS_PER_PARTITION = "qpid.jdbcstore.bonecp.minConnectionsPerPartition"; - - private final Set _supportedAttributes = unmodifiableSet(new HashSet(asList(PARTITION_COUNT, MAX_CONNECTIONS_PER_PARTITION, MIN_CONNECTIONS_PER_PARTITION))); - - @Override - public String getType() - { - return "BONECP"; - } - - public ConnectionProvider getConnectionProvider(String connectionUrl, String username, String password, Map providerAttributes) - throws SQLException - { - return new BoneCPConnectionProvider(connectionUrl, username, password, providerAttributes); - } - - @Override - public Set getProviderAttributeNames() - { - return _supportedAttributes; - } -} diff --git a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/js/qpid/management/store/pool/bonecp/add.js b/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/js/qpid/management/store/pool/bonecp/add.js deleted file mode 100644 index 0ec991ea16..0000000000 --- a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/js/qpid/management/store/pool/bonecp/add.js +++ /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. - * - */ -define(["dojo/_base/xhr", - "dojo/dom", - "dojo/dom-construct", - "dojo/_base/window", - "dijit/registry", - "dojo/parser", - "dojo/_base/array", - "dojo/_base/event", - "dojo/_base/json", - "dojo/string", - "dojo/store/Memory", - "dijit/form/FilteringSelect", - "dojo/domReady!"], - function (xhr, dom, construct, win, registry, parser, array, event, json, string, Memory, FilteringSelect) { - return { - show: function(data) { - data.context.addInheritedContext({ - "qpid.jdbcstore.bonecp.partitionCount": "4", - "qpid.jdbcstore.bonecp.minConnectionsPerPartition": "5", - "qpid.jdbcstore.bonecp.maxConnectionsPerPartition": "10" - }); - } - }; - }); diff --git a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/js/qpid/management/store/pool/bonecp/edit.js b/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/js/qpid/management/store/pool/bonecp/edit.js deleted file mode 100644 index 6876e3850b..0000000000 --- a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/js/qpid/management/store/pool/bonecp/edit.js +++ /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. - * - */ -define(["dojo/_base/xhr", - "dojo/dom", - "dojo/dom-construct", - "dojo/_base/window", - "dijit/registry", - "dojo/parser", - "qpid/common/util", - "dojo/domReady!"], - function (xhr, dom, construct, win, registry, parser, util) { - return { - show: function(data) { } - }; - }); diff --git a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/js/qpid/management/store/pool/bonecp/show.js b/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/js/qpid/management/store/pool/bonecp/show.js deleted file mode 100644 index 3d15cdbc37..0000000000 --- a/qpid/java/broker-plugins/jdbc-provider-bone/src/main/java/resources/js/qpid/management/store/pool/bonecp/show.js +++ /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. - * - */ -define(["dojo/_base/xhr", - "dojo/_base/lang", - "dojo/_base/connect", - "dojo/parser", - "dojo/string", - "dojox/html/entities", - "dojo/query", - "dojo/json", - "dojo/domReady!"], - function (xhr, lang, connect, parser, json, entities, query, json) - { - var fieldNames = ["maxConnectionsPerPartition", "minConnectionsPerPartition", "partitionCount"]; - - function BoneCP(data) - { - var containerNode = data.containerNode; - this.parent = data.parent; - var that = this; - xhr.get({url: "store/pool/bonecp/show.html", - sync: true, - load: function(template) { - containerNode.innerHTML = template; - parser.parse(containerNode).then(function(instances) - { - for(var i=0; i -
-
-
-
-
Partition Count:
-
-
-
-
Minimum connections per Partition:
-
-
-
-
Maximum connections per Partition:
-
-
-
-
-
- diff --git a/qpid/java/broker-plugins/jdbc-store/pom.xml b/qpid/java/broker-plugins/jdbc-store/pom.xml deleted file mode 100644 index a330ab12d5..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/pom.xml +++ /dev/null @@ -1,91 +0,0 @@ - - - - 4.0.0 - - - org.apache.qpid - qpid-java-build - 0.32-SNAPSHOT - ../../pom.xml - - - qpid-broker-plugins-jdbc-store - Qpid JDBC Message Store Broker Plug-in - JDBC message store broker plug-in - - - - org.apache.qpid - qpid-broker-core - ${project.version} - provided - - - - org.apache.qpid - qpid-broker-codegen - ${project.version} - true - - - - log4j - log4j - ${log4j-version} - - - - - org.apache.qpid - qpid-test-utils - ${project.version} - test - - - - org.apache.qpid - qpid-broker-core - ${project.version} - test-jar - test - - - - org.apache.derby - derby - ${derby-version} - test - - - - - - - src/main/resources - - - src/main/java - - resources/ - - - - - - diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/DefaultConnectionProvider.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/DefaultConnectionProvider.java deleted file mode 100644 index a96d46af18..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/DefaultConnectionProvider.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.jdbc; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -class DefaultConnectionProvider implements ConnectionProvider -{ - private final String _connectionUrl; - private final String _username; - private final String _password; - - public DefaultConnectionProvider(String connectionUrl, String username, String password) - { - _connectionUrl = connectionUrl; - _username = username; - _password = password; - } - - @Override - public Connection getConnection() throws SQLException - { - if (_username == null) - { - return DriverManager.getConnection(_connectionUrl); - } - else - { - return DriverManager.getConnection(_connectionUrl, _username, _password); - } - } - - @Override - public void close() throws SQLException - { - } -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/DefaultConnectionProviderFactory.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/DefaultConnectionProviderFactory.java deleted file mode 100644 index 0a829696f0..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/DefaultConnectionProviderFactory.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.store.jdbc; - -import org.apache.qpid.server.plugin.JDBCConnectionProviderFactory; -import org.apache.qpid.server.plugin.PluggableService; - -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -@PluggableService -public class DefaultConnectionProviderFactory implements JDBCConnectionProviderFactory -{ - public static final String TYPE = "NONE"; - - @Override - public String getType() - { - return TYPE; - } - - @Override - public ConnectionProvider getConnectionProvider(String connectionUrl, String username, String password, Map providerAttributes) - { - return new DefaultConnectionProvider(connectionUrl, username, password); - } - - @Override - public Set getProviderAttributeNames() - { - return Collections.emptySet(); - } - -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericAbstractJDBCMessageStore.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericAbstractJDBCMessageStore.java deleted file mode 100644 index e062af45a7..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericAbstractJDBCMessageStore.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.server.store.jdbc; - - -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.store.StoreException; -import org.apache.qpid.server.util.FutureResult; -import org.apache.qpid.server.store.Transaction; - -public abstract class GenericAbstractJDBCMessageStore extends org.apache.qpid.server.store.AbstractJDBCMessageStore -{ - private final AtomicBoolean _messageStoreOpen = new AtomicBoolean(false); - private final List _transactions = new CopyOnWriteArrayList<>(); - - private ConfiguredObject _parent; - - @Override - public final void openMessageStore(ConfiguredObject parent) - { - if (_messageStoreOpen.compareAndSet(false, true)) - { - _parent = parent; - - doOpen(parent); - - createOrOpenMessageStoreDatabase(); - setMaximumMessageId(); - } - } - - protected abstract void doOpen(final ConfiguredObject parent) - throws StoreException; - - @Override - public final void upgradeStoreStructure() throws StoreException - { - checkMessageStoreOpen(); - - upgrade(_parent); - } - - @Override - public final void closeMessageStore() - { - if (_messageStoreOpen.compareAndSet(true, false)) - { - try - { - while(!_transactions.isEmpty()) - { - RecordedJDBCTransaction txn = _transactions.get(0); - txn.abortTran(); - } - } - finally - { - doClose(); - super.closeMessageStore(); - } - - } - } - - protected abstract void doClose(); - - protected boolean isMessageStoreOpen() - { - return _messageStoreOpen.get(); - } - - @Override - protected void checkMessageStoreOpen() - { - if (!_messageStoreOpen.get()) - { - throw new IllegalStateException("Message store is not open"); - } - } - - @Override - protected void storedSizeChange(int contentSize) - { - } - - @Override - public Transaction newTransaction() - { - return new RecordedJDBCTransaction(); - } - - - private class RecordedJDBCTransaction extends JDBCTransaction - { - private RecordedJDBCTransaction() - { - super(); - GenericAbstractJDBCMessageStore.this._transactions.add(this); - } - - @Override - public void commitTran() - { - try - { - super.commitTran(); - } - finally - { - GenericAbstractJDBCMessageStore.this._transactions.remove(this); - } - } - - @Override - public FutureResult commitTranAsync() - { - try - { - return super.commitTranAsync(); - } - finally - { - GenericAbstractJDBCMessageStore.this._transactions.remove(this); - } - } - - @Override - public void abortTran() - { - try - { - super.abortTran(); - } - finally - { - GenericAbstractJDBCMessageStore.this._transactions.remove(this); - } - } - } -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCConfigurationStore.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCConfigurationStore.java deleted file mode 100644 index cd6ca85ee5..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCConfigurationStore.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.store.jdbc; - - -import java.io.File; -import java.nio.charset.Charset; -import java.security.PrivilegedAction; -import java.sql.Blob; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; - -import javax.security.auth.Subject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.plugin.JDBCConnectionProviderFactory; -import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.store.AbstractJDBCConfigurationStore; -import org.apache.qpid.server.store.ConfiguredObjectRecord; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.MessageStoreProvider; -import org.apache.qpid.server.store.StoreException; - -/** - * Implementation of a DurableConfigurationStore backed by Generic JDBC Database - * that also provides a MessageStore. - */ -public class GenericJDBCConfigurationStore extends AbstractJDBCConfigurationStore implements MessageStoreProvider -{ - private static final Charset UTF8_CHARSET = Charset.forName("UTF-8"); - - private static final Logger LOGGER = LoggerFactory.getLogger(GenericJDBCConfigurationStore.class); - - private final AtomicBoolean _configurationStoreOpen = new AtomicBoolean(); - private final MessageStore _providedMessageStore = new ProvidedMessageStore(); - - private String _connectionURL; - private ConnectionProvider _connectionProvider; - - private String _blobType; - private String _varBinaryType; - private String _bigIntType; - private boolean _useBytesMethodsForBlob; - - private ConfiguredObject _parent; - private final Class _rootClass; - - public GenericJDBCConfigurationStore(final Class rootClass) - { - _rootClass = rootClass; - } - - @Override - public void openConfigurationStore(ConfiguredObject parent, - final boolean overwrite, - final ConfiguredObjectRecord... initialRecords) - throws StoreException - { - if (_configurationStoreOpen.compareAndSet(false, true)) - { - _parent = parent; - - JDBCSettings settings = (JDBCSettings)parent; - _connectionURL = settings.getConnectionUrl(); - - JDBCDetails details = JDBCDetails.getDetailsForJdbcUrl(_connectionURL, parent); - - if (!details.isKnownVendor() && getLogger().isInfoEnabled()) - { - getLogger().info("Do not recognize vendor from connection URL: " + _connectionURL - + " Using fallback settings " + details); - } - if (details.isOverridden() && getLogger().isInfoEnabled()) - { - getLogger().info("One or more JDBC details were overridden from context. " - + " Using settings : " + details); - } - - String connectionPoolType = settings.getConnectionPoolType() == null ? DefaultConnectionProviderFactory.TYPE : settings.getConnectionPoolType(); - - JDBCConnectionProviderFactory connectionProviderFactory = - JDBCConnectionProviderFactory.FACTORIES.get(connectionPoolType); - if(connectionProviderFactory == null) - { - LOGGER.warn("Unknown connection pool type: " - + connectionPoolType - + ". no connection pooling will be used"); - connectionProviderFactory = new DefaultConnectionProviderFactory(); - } - - try - { - Map providerAttributes = new HashMap<>(); - Set providerAttributeNames = new HashSet(connectionProviderFactory.getProviderAttributeNames()); - providerAttributeNames.retainAll(parent.getContextKeys(false)); - for(String attr : providerAttributeNames) - { - providerAttributes.put(attr, parent.getContextValue(String.class, attr)); - } - - _connectionProvider = connectionProviderFactory.getConnectionProvider(_connectionURL, - settings.getUsername(), - getPlainTextPassword(settings), - providerAttributes); - } - catch (SQLException e) - { - throw new StoreException("Failed to create connection provider for connectionUrl: " + _connectionURL + - " and username: " + settings.getUsername(), e); - } - _blobType = details.getBlobType(); - _varBinaryType = details.getVarBinaryType(); - _useBytesMethodsForBlob = details.isUseBytesMethodsForBlob(); - _bigIntType = details.getBigintType(); - - createOrOpenConfigurationStoreDatabase(overwrite); - if(hasNoConfigurationEntries()) - { - update(true, initialRecords); - } - } - } - - @Override - public void upgradeStoreStructure() throws StoreException - { - checkConfigurationStoreOpen(); - upgradeIfNecessary(_parent); - } - - @Override - protected Connection getConnection() throws SQLException - { - return _connectionProvider.getConnection(); - } - - @Override - public void closeConfigurationStore() throws StoreException - { - if (_configurationStoreOpen.compareAndSet(true, false)) - { - try - { - _connectionProvider.close(); - } - catch (SQLException e) - { - throw new StoreException("Unable to close connection provider ", e); - } - } - } - - @Override - protected String getSqlBlobType() - { - return _blobType; - } - - @Override - protected String getSqlVarBinaryType(int size) - { - return String.format(_varBinaryType, size); - } - - @Override - public String getSqlBigIntType() - { - return _bigIntType; - } - - @Override - protected String getBlobAsString(ResultSet rs, int col) throws SQLException - { - byte[] bytes; - if(_useBytesMethodsForBlob) - { - bytes = rs.getBytes(col); - return new String(bytes,UTF8_CHARSET); - } - else - { - Blob blob = rs.getBlob(col); - if(blob == null) - { - return null; - } - bytes = blob.getBytes(1, (int)blob.length()); - } - return new String(bytes, UTF8_CHARSET); - - } - - protected byte[] getBlobAsBytes(ResultSet rs, int col) throws SQLException - { - if(_useBytesMethodsForBlob) - { - return rs.getBytes(col); - } - else - { - Blob dataAsBlob = rs.getBlob(col); - return dataAsBlob.getBytes(1,(int) dataAsBlob.length()); - - } - } - - @Override - protected void checkConfigurationStoreOpen() - { - if (!_configurationStoreOpen.get()) - { - throw new IllegalStateException("Configuration store is not open"); - } - } - - @Override - protected Logger getLogger() - { - return LOGGER; - } - - @Override - public MessageStore getMessageStore() - { - return _providedMessageStore; - } - - protected String getPlainTextPassword(final JDBCSettings settings) - { - return Subject.doAs(SecurityManager.getSubjectWithAddedSystemRights(), new PrivilegedAction() - { - @Override - public String run() - { - return settings.getPassword(); - } - }); - } - - private class ProvidedMessageStore extends GenericAbstractJDBCMessageStore - { - @Override - protected void doOpen(final ConfiguredObject parent) - { - // Nothing to do, store provided by DerbyConfigurationStore - } - - @Override - protected Connection getConnection() throws SQLException - { - return GenericJDBCConfigurationStore.this.getConnection(); - } - - @Override - protected void doClose() - { - // Nothing to do, store provided by DerbyConfigurationStore - } - - @Override - public String getStoreLocation() - { - return GenericJDBCConfigurationStore.this._connectionURL; - } - - @Override - public File getStoreLocationAsFile() - { - return null; - } - - @Override - protected Logger getLogger() - { - return GenericJDBCConfigurationStore.this.getLogger(); - } - - @Override - protected String getSqlBlobType() - { - return GenericJDBCConfigurationStore.this.getSqlBlobType(); - } - - @Override - protected String getSqlVarBinaryType(int size) - { - return GenericJDBCConfigurationStore.this.getSqlVarBinaryType(size); - } - - @Override - protected String getSqlBigIntType() - { - return GenericJDBCConfigurationStore.this.getSqlBigIntType(); - } - - @Override - protected byte[] getBlobAsBytes(final ResultSet rs, final int col) throws SQLException - { - return GenericJDBCConfigurationStore.this.getBlobAsBytes(rs, col); - } - } - - -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCMessageStore.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCMessageStore.java deleted file mode 100644 index 32ddd89833..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCMessageStore.java +++ /dev/null @@ -1,199 +0,0 @@ -/* -* -* Licensed to the Apache Software Foundation (ASF) under one -* or more contributor license agreements. See the NOTICE file -* distributed with this work for additional information -* regarding copyright ownership. The ASF licenses this file -* to you under the Apache License, Version 2.0 (the -* "License"); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* 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.jdbc; - - -import java.io.File; -import java.security.PrivilegedAction; -import java.sql.Blob; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import javax.security.auth.Subject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.plugin.JDBCConnectionProviderFactory; -import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.store.StoreException; - -/** - * Implementation of a MessageStore backed by a Generic JDBC Database. - */ -public class GenericJDBCMessageStore extends GenericAbstractJDBCMessageStore -{ - - private static final Logger _logger = LoggerFactory.getLogger(GenericJDBCMessageStore.class); - - protected String _connectionURL; - private ConnectionProvider _connectionProvider; - - private String _blobType; - private String _varBinaryType; - private String _bigIntType; - private boolean _useBytesMethodsForBlob; - - @Override - protected void doOpen(final ConfiguredObject parent) throws StoreException - { - JDBCSettings settings = (JDBCSettings)parent; - _connectionURL = settings.getConnectionUrl(); - - JDBCDetails details = JDBCDetails.getDetailsForJdbcUrl(_connectionURL, parent); - - if (!details.isKnownVendor() && getLogger().isInfoEnabled()) - { - getLogger().info("Do not recognize vendor from connection URL: " + _connectionURL - + " Using fallback settings " + details); - } - if (details.isOverridden() && getLogger().isInfoEnabled()) - { - getLogger().info("One or more JDBC details were overridden from context. " - + " Using settings : " + details); - } - - _blobType = details.getBlobType(); - _varBinaryType = details.getVarBinaryType(); - _useBytesMethodsForBlob = details.isUseBytesMethodsForBlob(); - _bigIntType = details.getBigintType(); - - String connectionPoolType = settings.getConnectionPoolType() == null ? DefaultConnectionProviderFactory.TYPE : settings.getConnectionPoolType(); - - JDBCConnectionProviderFactory connectionProviderFactory = - JDBCConnectionProviderFactory.FACTORIES.get(connectionPoolType); - if(connectionProviderFactory == null) - { - _logger.warn("Unknown connection pool type: " + connectionPoolType + ". No connection pooling will be used"); - connectionProviderFactory = new DefaultConnectionProviderFactory(); - } - - try - { - Map providerAttributes = new HashMap<>(); - Set providerAttributeNames = new HashSet(connectionProviderFactory.getProviderAttributeNames()); - providerAttributeNames.retainAll(parent.getContextKeys(false)); - for(String attr : providerAttributeNames) - { - providerAttributes.put(attr, parent.getContextValue(String.class, attr)); - } - - _connectionProvider = connectionProviderFactory.getConnectionProvider(_connectionURL, - settings.getUsername(), - getPlainTextPassword(settings), - providerAttributes); - } - catch (SQLException e) - { - throw new StoreException("Failed to create connection provider for connectionUrl: " + _connectionURL + - " and username: " + settings.getUsername()); - } - - } - - @Override - protected Connection getConnection() throws SQLException - { - return _connectionProvider.getConnection(); - } - - protected void doClose() - { - try - { - _connectionProvider.close(); - } - catch (SQLException e) - { - throw new StoreException("Unable to close connection provider ", e); - } - } - - - @Override - protected Logger getLogger() - { - return _logger; - } - - @Override - protected String getSqlBlobType() - { - return _blobType; - } - - @Override - protected String getSqlVarBinaryType(int size) - { - return String.format(_varBinaryType, size); - } - - @Override - protected byte[] getBlobAsBytes(ResultSet rs, int col) throws SQLException - { - if(_useBytesMethodsForBlob) - { - return rs.getBytes(col); - } - else - { - Blob dataAsBlob = rs.getBlob(col); - return dataAsBlob.getBytes(1,(int) dataAsBlob.length()); - - } - } - - @Override - public String getSqlBigIntType() - { - return _bigIntType; - } - - @Override - public String getStoreLocation() - { - return _connectionURL; - } - - @Override - public File getStoreLocationAsFile() - { - return null; - } - - protected String getPlainTextPassword(final JDBCSettings settings) - { - return Subject.doAs(SecurityManager.getSubjectWithAddedSystemRights(), new PrivilegedAction() - { - @Override - public String run() - { - return settings.getPassword(); - } - }); - } -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCDetails.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCDetails.java deleted file mode 100644 index eec2d49a80..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCDetails.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.store.jdbc; - -import java.util.AbstractMap; -import java.util.AbstractSet; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import org.apache.qpid.server.model.ConfiguredObject; - -public abstract class JDBCDetails -{ - public static final String CONTEXT_JDBCSTORE_BIGINTTYPE = "qpid.jdbcstore.bigIntType"; - public static final String CONTEXT_JDBCSTORE_VARBINARYTYPE = "qpid.jdbcstore.varBinaryType"; - public static final String CONTEXT_JDBCSTORE_BLOBTYPE = "qpid.jdbcstore.blobType"; - public static final String CONTEXT_JDBCSTORE_USEBYTESFORBLOB = "qpid.jdbcstore.useBytesForBlob"; - - public abstract String getVendor(); - - public abstract String getBlobType(); - - public abstract String getVarBinaryType(); - - public abstract String getBigintType(); - - public abstract boolean isUseBytesMethodsForBlob(); - - public abstract boolean isKnownVendor(); - - public abstract boolean isOverridden(); - - static class KnownJDBCDetails extends JDBCDetails - { - private static final JDBCDetails FALLBACK = new KnownJDBCDetails("fallback", "blob", "varchar(%d) for bit data", "bigint", false, - false); - private static final JDBCDetails ORACLE = new KnownJDBCDetails("oracle", "blob", "raw(%d)", "number", false, - true); - private static final JDBCDetails SYBASE = new KnownJDBCDetails("sybase", "image", "varbinary(%d)", "bigint", false, - true); - private static final JDBCDetails POSTGRES = new KnownJDBCDetails("postgresql", "bytea", "bytea", "bigint", true, - true); - private static final JDBCDetails DERBY = new KnownJDBCDetails("derby", "blob", "varchar(%d) for bit data", "bigint", false, - true); - - static - { - Map map = new HashMap<>(); - - try - { - map.put(ORACLE.getVendor(), ORACLE); - map.put(SYBASE.getVendor(), SYBASE); - map.put(POSTGRES.getVendor(), POSTGRES); - map.put(DERBY.getVendor(), DERBY); - map.put(FALLBACK.getVendor(), FALLBACK); - } - finally - { - VENDOR_DETAILS = Collections.unmodifiableMap(map); - } - } - - private final static Map VENDOR_DETAILS; - - private final String _vendor; - private final String _blobType; - private final String _varBinaryType; - private final String _bigintType; - private final boolean _useBytesMethodsForBlob; - private final boolean _isKnownVendor; - - KnownJDBCDetails(String vendor, - String blobType, - String varBinaryType, - String bigIntType, - boolean useBytesMethodsForBlob, - boolean knownVendor) - { - _vendor = vendor; - _blobType = blobType; - _varBinaryType = varBinaryType; - _bigintType = bigIntType; - _useBytesMethodsForBlob = useBytesMethodsForBlob; - _isKnownVendor = knownVendor; - } - - @Override - public String getVendor() - { - return _vendor; - } - - @Override - public String getBlobType() - { - return _blobType; - } - - @Override - public String getVarBinaryType() - { - return _varBinaryType; - } - - @Override - public boolean isUseBytesMethodsForBlob() - { - return _useBytesMethodsForBlob; - } - - @Override - public String getBigintType() - { - return _bigintType; - } - - @Override - public boolean isKnownVendor() - { - return _isKnownVendor; - } - - @Override - public boolean isOverridden() - { - return false; - } - - } - - @Override - public String toString() - { - return "JDBCDetails{" + - "vendor='" + getVendor() + '\'' + - ", blobType='" + getBlobType() + '\'' + - ", varBinaryType='" + getVarBinaryType() + '\'' + - ", bigIntType='" + getBigintType() + '\'' + - ", useBytesMethodsForBlob=" + isUseBytesMethodsForBlob() + - ", knownVendor=" + isKnownVendor() + - ", overridden=" + isOverridden() + - '}'; - } - - @Override - public boolean equals(final Object o) - { - if (this == o) - { - return true; - } - if (o == null || getClass() != o.getClass()) - { - return false; - } - - final JDBCDetails that = (JDBCDetails) o; - - if (isKnownVendor() != that.isKnownVendor()) - { - return false; - } - if (isOverridden() != that.isOverridden()) - { - return false; - } - if (isUseBytesMethodsForBlob() != that.isUseBytesMethodsForBlob()) - { - return false; - } - if (getBigintType() != null ? !getBigintType().equals(that.getBigintType()) : that.getBigintType() != null) - { - return false; - } - if (getBlobType() != null ? !getBlobType().equals(that.getBlobType()) : that.getBlobType() != null) - { - return false; - } - if (getVarBinaryType() != null ? !getVarBinaryType().equals(that.getVarBinaryType()) : that.getVarBinaryType() != null) - { - return false; - } - if (getVendor() != null ? !getVendor().equals(that.getVendor()) : that.getVendor() != null) - { - return false; - } - - return true; - } - - @Override - public int hashCode() - { - int result = getVendor() != null ? getVendor().hashCode() : 0; - result = 31 * result + (getBlobType() != null ? getBlobType().hashCode() : 0); - result = 31 * result + (getVarBinaryType() != null ? getVarBinaryType().hashCode() : 0); - result = 31 * result + (getBigintType() != null ? getBigintType().hashCode() : 0); - result = 31 * result + (isUseBytesMethodsForBlob() ? 1 : 0); - result = 31 * result + (isKnownVendor() ? 1 : 0); - result = 31 * result + (isOverridden() ? 1 : 0); - return result; - } - - public static JDBCDetails getDetailsForJdbcUrl(String jdbcUrl, final ConfiguredObject object) - { - final Set contextKeys = object.getContextKeys(false); - Map mapConversion = new AbstractMap() - { - @Override - public Set> entrySet() - { - return new AbstractSet>() - { - @Override - public Iterator> iterator() - { - final Iterator underlying = contextKeys.iterator(); - return new Iterator>() - { - @Override - public boolean hasNext() - { - return underlying.hasNext(); - } - - @Override - public Entry next() - { - final String key = underlying.next(); - final String value = object.getContextValue(String.class, key); - return new Entry() - { - - @Override - public String getKey() - { - return key; - } - - @Override - public String getValue() - { - return value; - } - - @Override - public String setValue(final String value) - { - throw new UnsupportedOperationException(); - } - }; - - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - }; - } - - @Override - public int size() - { - return contextKeys.size(); - } - }; - } - }; - return getDetailsForJdbcUrl(jdbcUrl, mapConversion); - } - public static JDBCDetails getDetailsForJdbcUrl(String jdbcUrl, final Map contextMap) - { - String[] components = jdbcUrl.split(":", 3); - final JDBCDetails details; - if(components.length >= 2) - { - String vendor = components[1]; - if (KnownJDBCDetails.VENDOR_DETAILS.containsKey(vendor)) - { - details = KnownJDBCDetails.VENDOR_DETAILS.get(vendor); - } - else - { - details = KnownJDBCDetails.FALLBACK; - } - } - else - { - details = KnownJDBCDetails.FALLBACK; - } - - - return new JDBCDetails() - { - @Override - public String getVendor() - { - return details.getVendor(); - } - - @Override - public String getBlobType() - { - return contextMap.containsKey(CONTEXT_JDBCSTORE_BLOBTYPE) - ? String.valueOf(contextMap.get(CONTEXT_JDBCSTORE_BLOBTYPE)) : details.getBlobType(); - } - - @Override - public String getVarBinaryType() - { - return contextMap.containsKey(CONTEXT_JDBCSTORE_VARBINARYTYPE) - ? String.valueOf(contextMap.get(CONTEXT_JDBCSTORE_VARBINARYTYPE)) : details.getVarBinaryType(); - } - - @Override - public String getBigintType() - { - return contextMap.containsKey(CONTEXT_JDBCSTORE_BIGINTTYPE) - ? String.valueOf(contextMap.get(CONTEXT_JDBCSTORE_BIGINTTYPE)) : details.getBigintType(); - } - - @Override - public boolean isUseBytesMethodsForBlob() - { - return contextMap.containsKey(CONTEXT_JDBCSTORE_USEBYTESFORBLOB) - ? Boolean.parseBoolean(contextMap.get(CONTEXT_JDBCSTORE_USEBYTESFORBLOB)) : details.isUseBytesMethodsForBlob(); - } - - @Override - public boolean isKnownVendor() - { - return details.isKnownVendor(); - } - - @Override - public boolean isOverridden() - { - return contextMap.containsKey(CONTEXT_JDBCSTORE_USEBYTESFORBLOB) - || contextMap.containsKey(CONTEXT_JDBCSTORE_BIGINTTYPE) - || contextMap.containsKey(CONTEXT_JDBCSTORE_VARBINARYTYPE) - || contextMap.containsKey(CONTEXT_JDBCSTORE_BLOBTYPE); - } - }; - - } - -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSettings.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSettings.java deleted file mode 100644 index d784ece0e4..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSettings.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.jdbc; - -import org.apache.qpid.server.store.Settings; - -public interface JDBCSettings extends Settings -{ - String getConnectionUrl(); - - String getConnectionPoolType(); - - String getUsername(); - - String getPassword(); -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSystemConfig.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSystemConfig.java deleted file mode 100644 index 9fe64577bb..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSystemConfig.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.store.jdbc; - -import org.apache.qpid.server.model.ManagedAttribute; -import org.apache.qpid.server.model.SystemConfig; - -public interface JDBCSystemConfig> extends SystemConfig, JDBCSettings -{ - @ManagedAttribute(mandatory=true, defaultValue = "${systemConfig.connectionUrl}") - String getConnectionUrl(); - - @ManagedAttribute(defaultValue=DefaultConnectionProviderFactory.TYPE) - String getConnectionPoolType(); - - @ManagedAttribute(defaultValue = "${systemConfig.username}") - String getUsername(); - - @ManagedAttribute(secure=true, defaultValue = "${systemConfig.password}") - String getPassword(); -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSystemConfigImpl.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSystemConfigImpl.java deleted file mode 100644 index 9c3d33fc04..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSystemConfigImpl.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.store.jdbc; - -import java.util.Map; - -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.LogRecorder; -import org.apache.qpid.server.model.AbstractSystemConfig; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.BrokerShutdownProvider; -import org.apache.qpid.server.model.ManagedAttributeField; -import org.apache.qpid.server.model.ManagedObject; -import org.apache.qpid.server.model.SystemConfigFactoryConstructor; -import org.apache.qpid.server.store.DurableConfigurationStore; - -@ManagedObject( category = false, type = JDBCSystemConfigImpl.SYSTEM_CONFIG_TYPE) -public class JDBCSystemConfigImpl extends AbstractSystemConfig implements JDBCSystemConfig -{ - public static final String SYSTEM_CONFIG_TYPE = "JDBC"; - - @ManagedAttributeField - private String _connectionUrl; - @ManagedAttributeField - private String _connectionPoolType; - @ManagedAttributeField - private String _username; - @ManagedAttributeField - private String _password; - - @SystemConfigFactoryConstructor - public JDBCSystemConfigImpl(final TaskExecutor taskExecutor, - final EventLogger eventLogger, - final LogRecorder logRecorder, - final Map attributes, - final BrokerShutdownProvider brokerShutdownProvider) - { - super(taskExecutor, eventLogger, logRecorder, attributes, brokerShutdownProvider); - } - - @Override - protected DurableConfigurationStore createStoreObject() - { - return new GenericJDBCConfigurationStore(Broker.class); - } - - @Override - public String getConnectionUrl() - { - return _connectionUrl; - } - - @Override - public String getConnectionPoolType() - { - return _connectionPoolType; - } - - @Override - public String getUsername() - { - return _username; - } - - @Override - public String getPassword() - { - return _password; - } -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhost/jdbc/JDBCVirtualHost.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhost/jdbc/JDBCVirtualHost.java deleted file mode 100644 index 8608848d98..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhost/jdbc/JDBCVirtualHost.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.jdbc; - -import org.apache.qpid.server.exchange.ExchangeImpl; -import org.apache.qpid.server.model.ManagedAttribute; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.store.jdbc.DefaultConnectionProviderFactory; -import org.apache.qpid.server.store.jdbc.JDBCSettings; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; - -public interface JDBCVirtualHost> extends VirtualHostImpl, ExchangeImpl>, - JDBCSettings -{ - @ManagedAttribute(mandatory=true) - String getConnectionUrl(); - - @ManagedAttribute(defaultValue=DefaultConnectionProviderFactory.TYPE) - String getConnectionPoolType(); - - @ManagedAttribute - String getUsername(); - - @ManagedAttribute(secure=true) - String getPassword(); -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhost/jdbc/JDBCVirtualHostImpl.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhost/jdbc/JDBCVirtualHostImpl.java deleted file mode 100644 index 434e887596..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhost/jdbc/JDBCVirtualHostImpl.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.virtualhost.jdbc; - -import org.apache.qpid.server.model.ManagedAttributeField; -import org.apache.qpid.server.model.ManagedObject; -import org.apache.qpid.server.model.ManagedObjectFactoryConstructor; -import org.apache.qpid.server.model.VirtualHostNode; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.jdbc.GenericJDBCMessageStore; -import org.apache.qpid.server.virtualhost.AbstractVirtualHost; - -import java.util.Map; - -@ManagedObject(category = false, type = JDBCVirtualHostImpl.VIRTUAL_HOST_TYPE) -public class JDBCVirtualHostImpl extends AbstractVirtualHost implements JDBCVirtualHost -{ - public static final String VIRTUAL_HOST_TYPE = "JDBC"; - - @ManagedAttributeField - private String _connectionUrl; - - @ManagedAttributeField - private String _connectionPoolType; - - @ManagedAttributeField - private String _username; - - @ManagedAttributeField - private String _password; - - @ManagedObjectFactoryConstructor - public JDBCVirtualHostImpl(final Map attributes, - final VirtualHostNode virtualHostNode) - { - super(attributes, virtualHostNode); - } - - @Override - protected MessageStore createMessageStore() - { - return new GenericJDBCMessageStore(); - } - - @Override - public String getConnectionUrl() - { - return _connectionUrl; - } - - @Override - public String getConnectionPoolType() - { - return _connectionPoolType; - } - - @Override - public String getUsername() - { - return _username; - } - - @Override - public String getPassword() - { - return _password; - } - - @Override - public String toString() - { - return getClass().getSimpleName() + " [id=" + getId() + ", name=" + getName() + - ", connectionUrl=" + getConnectionUrl() + - ", connectionPoolType=" + getConnectionPoolType() + - ", username=" + getUsername() + "]"; - } -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhostnode/jdbc/JDBCVirtualHostNode.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhostnode/jdbc/JDBCVirtualHostNode.java deleted file mode 100644 index 0ac75b3877..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhostnode/jdbc/JDBCVirtualHostNode.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.virtualhostnode.jdbc; - -import org.apache.qpid.server.model.ManagedAttribute; -import org.apache.qpid.server.model.VirtualHostNode; -import org.apache.qpid.server.store.jdbc.DefaultConnectionProviderFactory; -import org.apache.qpid.server.store.jdbc.JDBCSettings; - -public interface JDBCVirtualHostNode> extends VirtualHostNode, JDBCSettings -{ - @ManagedAttribute(mandatory=true) - String getConnectionUrl(); - - @ManagedAttribute(defaultValue=DefaultConnectionProviderFactory.TYPE) - String getConnectionPoolType(); - - @ManagedAttribute - String getUsername(); - - @ManagedAttribute(secure=true) - String getPassword(); -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhostnode/jdbc/JDBCVirtualHostNodeImpl.java b/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhostnode/jdbc/JDBCVirtualHostNodeImpl.java deleted file mode 100644 index cb20549b80..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhostnode/jdbc/JDBCVirtualHostNodeImpl.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.virtualhostnode.jdbc; - -import java.util.Collection; -import java.util.Collections; -import java.util.Map; - -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ManagedAttributeField; -import org.apache.qpid.server.model.ManagedObject; -import org.apache.qpid.server.model.ManagedObjectFactoryConstructor; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.store.DurableConfigurationStore; -import org.apache.qpid.server.store.jdbc.GenericJDBCConfigurationStore; -import org.apache.qpid.server.virtualhostnode.AbstractStandardVirtualHostNode; - -@ManagedObject(type = JDBCVirtualHostNodeImpl.VIRTUAL_HOST_NODE_TYPE, category = false , - validChildTypes = "org.apache.qpid.server.virtualhostnode.jdbc.JDBCVirtualHostNodeImpl#getSupportedChildTypes()") -public class JDBCVirtualHostNodeImpl extends AbstractStandardVirtualHostNode implements JDBCVirtualHostNode -{ - public static final String VIRTUAL_HOST_NODE_TYPE = "JDBC"; - - @ManagedAttributeField - private String _connectionUrl; - - @ManagedAttributeField - private String _connectionPoolType; - - @ManagedAttributeField - private String _username; - - @ManagedAttributeField - private String _password; - - @ManagedObjectFactoryConstructor - public JDBCVirtualHostNodeImpl(Map attributes, Broker parent) - { - super(attributes, parent); - } - - @Override - protected void writeLocationEventLog() - { - } - - @Override - protected DurableConfigurationStore createConfigurationStore() - { - return new GenericJDBCConfigurationStore(VirtualHost.class); - } - - @Override - public String getConnectionUrl() - { - return _connectionUrl; - } - - @Override - public String getConnectionPoolType() - { - return _connectionPoolType; - } - - @Override - public String getUsername() - { - return _username; - } - - @Override - public String getPassword() - { - return _password; - } - - @Override - public String toString() - { - return getClass().getSimpleName() + " [id=" + getId() + ", name=" + getName() + - ", connectionUrl=" + getConnectionUrl() + - ", connectionPoolType=" + getConnectionPoolType() + - ", username=" + getUsername() + "]"; - } - - - public static Map> getSupportedChildTypes() - { - return Collections.singletonMap(VirtualHost.class.getSimpleName(), getSupportedVirtualHostTypes(true)); - } -} diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/store/pool/none/add.js b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/store/pool/none/add.js deleted file mode 100644 index 44405c610b..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/store/pool/none/add.js +++ /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. - * - */ -define(["dojo/_base/xhr", - "dojo/dom", - "dojo/dom-construct", - "dojo/_base/window", - "dijit/registry", - "dojo/parser", - "dojo/_base/array", - "dojo/_base/event", - "dojo/_base/json", - "dojo/string", - "dojo/store/Memory", - "dijit/form/FilteringSelect", - "dojo/domReady!"], - function (xhr, dom, construct, win, registry, parser, array, event, json, string, Memory, FilteringSelect) { - return { - show: function(data) - { - data.context.removeDynamicallyAddedInheritedContext(); - } - }; - }); diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/store/pool/none/edit.js b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/store/pool/none/edit.js deleted file mode 100644 index 675a919b3d..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/store/pool/none/edit.js +++ /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. - * - */ -define([], - function () - { - return {show: function(data) {}}; - } -); diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/store/pool/none/show.js b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/store/pool/none/show.js deleted file mode 100644 index 39cb2bf507..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/store/pool/none/show.js +++ /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. - * - */ -define([], - function () - { - function NonePool(data) - { - } - - NonePool.prototype.update=function(data) - { - }; - - return NonePool; -}); diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhost/jdbc/add.js b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhost/jdbc/add.js deleted file mode 100644 index 8de6206373..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhost/jdbc/add.js +++ /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. - */ -define(["dojo/_base/xhr", - "dojo/_base/array", - "dojo/parser", - "dojo/dom", - "dojo/dom-construct", - "dojo/json", - "dojo/string", - "dojo/store/Memory", - "dijit/registry", - "dojo/text!virtualhost/jdbc/add.html", - "dojo/text!service/helper?action=pluginList&plugin=JDBCConnectionProviderFactory", - "qpid/common/util", - "dijit/form/ValidationTextBox", - "dijit/form/CheckBox", - "dojo/domReady!"], - function (xhr, array, parser, dom, domConstruct, json, string, Memory, registry, template, poolTypeJsonString, util) - { - return { - show: function (data) - { - var that = this; - this.containerNode = domConstruct.create("div", {innerHTML: template}, data.containerNode); - parser.parse(this.containerNode).then(function(instances) - { - that._postParse(data); - }); - }, - _postParse: function (data) - { - var that = this; - registry.byId("addVirtualHost.connectionUrl").set("regExpGen", util.jdbcUrlOrContextVarRegexp); - registry.byId("addVirtualHost.username").set("regExpGen", util.nameOrContextVarRegexp); - var poolTypes = json.parse(poolTypeJsonString); - var poolTypesData = []; - for (var i =0 ; i < poolTypes.length; i++) - { - poolTypesData[i]= {id: poolTypes[i], name: poolTypes[i]}; - } - var poolTypesStore = new Memory({ data: poolTypesData }); - var poolTypeControl = registry.byId("addVirtualHost.connectionPoolType"); - poolTypeControl.set("store", poolTypesStore); - poolTypeControl.set("value", "NONE"); - - var poolTypeFieldsDiv = dom.byId("addVirtualHost.poolSpecificDiv"); - poolTypeControl.on("change", - function(type) - { - if(type && string.trim(type) != "") - { - var widgets = registry.findWidgets(poolTypeFieldsDiv); - array.forEach(widgets, function(item) { item.destroyRecursive();}); - domConstruct.empty(poolTypeFieldsDiv); - require(["qpid/management/store/pool/"+type.toLowerCase()+"/add"], - function(poolType) - { - poolType.show({containerNode:poolTypeFieldsDiv, context: data.parent.virtualHostContext}); - }); - } - } - ); - } - }; - } -); diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhost/jdbc/edit.js b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhost/jdbc/edit.js deleted file mode 100644 index 4a2a3763bd..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhost/jdbc/edit.js +++ /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. - */ -define(["qpid/common/util", - "dojo/text!service/helper?action=pluginList&plugin=JDBCConnectionProviderFactory", - "dojo/_base/array", - "dojo/json", - "dojo/string", - "dojo/store/Memory", - "dojo/dom", - "dojo/dom-construct", - "dijit/registry", - "dojo/domReady!"], - function (util, poolTypeJsonString, array, json, string, Memory, dom, domConstruct, registry) - { - - return { - show: function(data) - { - var that = this; - util.parseHtmlIntoDiv(data.containerNode, "virtualhost/jdbc/edit.html", - function(){that._postParse(data)}); - }, - _postParse: function(data) - { - registry.byId("editVirtualHost.connectionUrl").set("regExpGen", util.jdbcUrlOrContextVarRegexp); - registry.byId("editVirtualHost.username").set("regExpGen", util.nameOrContextVarRegexp); - - var poolTypes = json.parse(poolTypeJsonString); - var poolTypesData = []; - for (var i =0 ; i < poolTypes.length; i++) - { - poolTypesData[i]= {id: poolTypes[i], name: poolTypes[i]}; - } - var poolTypesStore = new Memory({ data: poolTypesData }); - var poolTypeControl = registry.byId("editVirtualHost.connectionPoolType"); - poolTypeControl.set("store", poolTypesStore); - poolTypeControl.set("value", data.data.connectionPoolType); - - var passwordControl = registry.byId("editVirtualHost.password"); - if (data.data.password) - { - passwordControl.set("placeHolder", "*******"); - } - - var poolTypeFieldsDiv = dom.byId("editVirtualHost.poolSpecificDiv"); - poolTypeControl.on("change", - function(type) - { - if(type && string.trim(type) != "") - { - var widgets = registry.findWidgets(poolTypeFieldsDiv); - array.forEach(widgets, function(item) { item.destroyRecursive();}); - domConstruct.empty(poolTypeFieldsDiv); - - require(["qpid/management/store/pool/"+type.toLowerCase()+"/edit"], - function(poolType) - { - poolType.show({containerNode:poolTypeFieldsDiv, data: data.data, context: data.parent.context}) - }); - } - } - ); - } - }; - } -); diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhost/jdbc/show.js b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhost/jdbc/show.js deleted file mode 100644 index b717f2091d..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhost/jdbc/show.js +++ /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. - * - */ -define(["qpid/common/util", "dojo/query", "dojo/_base/array", "dojo/dom-construct", "dijit/registry", "dojo/domReady!"], - function (util, query, array, domConstruct, registry) - { - var fieldNames = ["connectionUrl", "username", "connectionPoolType"]; - - function JDBC(data) - { - var that = this; - util.buildUI(data.containerNode, data.parent, "virtualhostnode/jdbc/show.html", fieldNames, this, function() - { - that.usernameAttributeContainer=query(".usernameAttributeContainer", data.containerNode)[0]; - that.connectionPoolTypeAttributeContainer=query(".connectionPoolTypeAttributeContainer", data.containerNode)[0]; - }); - } - - JDBC.prototype.update = function(data) - { - var previousConnectionPoolType = this.connectionPoolType ? this.connectionPoolType.innerHTML : null; - util.updateUI(data, fieldNames, this); - this.usernameAttributeContainer.style.display = data.username ? "block" : "none"; - if (data.connectionPoolType && (!this.poolDetails || previousConnectionPoolType != data.connectionPoolType)) - { - var that = this; - require(["qpid/management/store/pool/" + data.connectionPoolType.toLowerCase() + "/show"], - function(PoolDetails) - { - var widgets = registry.findWidgets(that.connectionPoolTypeAttributeContainer); - array.forEach(widgets, function(item) { item.destroyRecursive();}); - domConstruct.empty(that.connectionPoolTypeAttributeContainer); - - that.poolDetails = new PoolDetails({containerNode:that.connectionPoolTypeAttributeContainer, parent: that}); - that.poolDetails.update(data); - } - ); - } - else - { - this.poolDetails.update(data); - } - } - - return JDBC; - } -); diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhostnode/jdbc/add.js b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhostnode/jdbc/add.js deleted file mode 100644 index 071c0c8b23..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhostnode/jdbc/add.js +++ /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. - * - */ -define(["dojo/_base/xhr", - "dojo/_base/array", - "dojo/parser", - "dojo/dom", - "dojo/dom-construct", - "dojo/json", - "dojo/string", - "dojo/store/Memory", - "dijit/registry", - "dojo/text!virtualhostnode/jdbc/add.html", - "dojo/text!service/helper?action=pluginList&plugin=JDBCConnectionProviderFactory", - "qpid/common/util", - "dijit/form/ValidationTextBox", - "dijit/form/CheckBox", - "dojo/domReady!"], - function (xhr, array, parser, dom, domConstruct, json, string, Memory, registry, template, poolTypeJsonString, util) - { - return { - show: function (data) - { - var that = this; - this.containerNode = domConstruct.create("div", {innerHTML: template}, data.containerNode); - parser.parse(this.containerNode).then(function(instances) - { - that._postParse(data); - }); - }, - _postParse: function(data) - { - var that = this; - registry.byId("addVirtualHostNode.connectionUrl").set("regExpGen", util.jdbcUrlOrContextVarRegexp); - registry.byId("addVirtualHostNode.username").set("regExpGen", util.nameOrContextVarRegexp); - - var poolTypes = json.parse(poolTypeJsonString); - var poolTypesData = []; - for (var i =0 ; i < poolTypes.length; i++) - { - poolTypesData[i]= {id: poolTypes[i], name: poolTypes[i]}; - } - var poolTypesStore = new Memory({ data: poolTypesData }); - var poolTypeControl = registry.byId("addVirtualHostNode.connectionPoolType"); - poolTypeControl.set("store", poolTypesStore); - poolTypeControl.set("value", "NONE"); - - var poolTypeFieldsDiv = dom.byId("addVirtualHostNode.poolSpecificDiv"); - poolTypeControl.on("change", - function(type) - { - if(type && string.trim(type) != "") - { - var widgets = registry.findWidgets(poolTypeFieldsDiv); - array.forEach(widgets, function(item) { item.destroyRecursive();}); - domConstruct.empty(poolTypeFieldsDiv); - require(["qpid/management/store/pool/"+type.toLowerCase()+"/add"], - function(poolType) - { - poolType.show({containerNode:poolTypeFieldsDiv, context: data.parent.virtualHostNodeContext}); - }); - } - } - ); - } - }; - } -); diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhostnode/jdbc/edit.js b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhostnode/jdbc/edit.js deleted file mode 100644 index cccfa95d4c..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhostnode/jdbc/edit.js +++ /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. - */ -define(["qpid/common/util", - "dojo/text!service/helper?action=pluginList&plugin=JDBCConnectionProviderFactory", - "dojo/_base/array", - "dojo/json", - "dojo/string", - "dojo/store/Memory", - "dojo/dom", - "dojo/dom-construct", - "dijit/registry", - "dojo/domReady!"], - function (util, poolTypeJsonString, array, json, string, Memory, dom, domConstruct, registry) - { - return { - show: function(data) - { - var that = this; - util.parseHtmlIntoDiv(data.containerNode, "virtualhostnode/jdbc/edit.html", function(){ that._postParse(data);}); - }, - _postParse: function(data) - { - registry.byId("editVirtualHostNode.connectionUrl").set("regExpGen", util.jdbcUrlOrContextVarRegexp); - registry.byId("editVirtualHostNode.username").set("regExpGen", util.nameOrContextVarRegexp); - - var poolTypes = json.parse(poolTypeJsonString); - var poolTypesData = []; - for (var i =0 ; i < poolTypes.length; i++) - { - poolTypesData[i]= {id: poolTypes[i], name: poolTypes[i]}; - } - var poolTypesStore = new Memory({ data: poolTypesData }); - var poolTypeControl = registry.byId("editVirtualHostNode.connectionPoolType"); - poolTypeControl.set("store", poolTypesStore); - poolTypeControl.set("value", data.data.connectionPoolType); - - var passwordControl = registry.byId("editVirtualHostNode.password"); - if (data.data.password) - { - passwordControl.set("placeHolder", "*******"); - } - - var poolTypeFieldsDiv = dom.byId("editVirtualHostNode.poolSpecificDiv"); - poolTypeControl.on("change", - function(type) - { - if(type && string.trim(type) != "") - { - var widgets = registry.findWidgets(poolTypeFieldsDiv); - array.forEach(widgets, function(item) { item.destroyRecursive();}); - domConstruct.empty(poolTypeFieldsDiv); - - require(["qpid/management/store/pool/"+type.toLowerCase()+"/edit"], - function(poolType) - { - poolType.show({containerNode:poolTypeFieldsDiv, data: data.data, context: data.parent.context}) - - if (!(data.data.state == "STOPPED" || data.data.state == "ERRORED")) - { - var widgets = registry.findWidgets(poolTypeFieldsDiv); - array.forEach(widgets, function(item) { item.set("disabled", true);}); - } - }); - } - } - ); - } - }; - } -); diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhostnode/jdbc/show.js b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhostnode/jdbc/show.js deleted file mode 100644 index 019962fc64..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/js/qpid/management/virtualhostnode/jdbc/show.js +++ /dev/null @@ -1,68 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -define(["qpid/common/util", "dojo/query", "dojo/_base/array", "dojo/dom-construct", "dijit/registry", "dojo/domReady!"], - function (util, query, array, domConstruct, registry) - { - var fieldNames = ["connectionUrl", "username", "connectionPoolType"]; - - function Jdbc(data) - { - this.parent = data.parent; - var that = this; - util.buildUI(data.containerNode, data.parent, "virtualhostnode/jdbc/show.html", fieldNames, this, - function() - { - that.usernameAttributeContainer=query(".usernameAttributeContainer", data.containerNode)[0]; - that.connectionPoolTypeAttributeContainer=query(".connectionPoolTypeAttributeContainer", data.containerNode)[0]; - }); - } - - Jdbc.prototype.update=function(data) - { - var previousConnectionPoolType = this.connectionPoolType ? this.connectionPoolType.innerHTML : null; - this.parent.editNodeButton.set("disabled", !(data.state == "STOPPED" || data.state == "ERRORED")); - util.updateUI(data, fieldNames, this); - - this.usernameAttributeContainer.style.display = data.username ? "block" : "none"; - if (data.connectionPoolType && (!this.poolDetails || previousConnectionPoolType != data.connectionPoolType)) - { - var that = this; - require(["qpid/management/store/pool/" + data.connectionPoolType.toLowerCase() + "/show"], - function(PoolDetails) - { - var widgets = registry.findWidgets(that.connectionPoolTypeAttributeContainer); - array.forEach(widgets, function(item) { item.destroyRecursive();}); - domConstruct.empty(that.connectionPoolTypeAttributeContainer); - - that.poolDetails = new PoolDetails({containerNode:that.connectionPoolTypeAttributeContainer, parent: that}); - that.poolDetails.update(data); - } - ); - } - else - { - this.poolDetails.update(data); - } - }; - - return Jdbc; -}); diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhost/jdbc/add.html b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhost/jdbc/add.html deleted file mode 100644 index 7fc7f17565..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhost/jdbc/add.html +++ /dev/null @@ -1,76 +0,0 @@ - -
-
-
JDBC Url*:
-
- -
-
-
-
Username*:
-
- -
-
-
-
Password*:
-
- -
-
-
-
Connection Pool*:
-
- -
-
- -
-
-
The virtual host will have the same name as the node.
-
diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhost/jdbc/edit.html b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhost/jdbc/edit.html deleted file mode 100644 index 10212079eb..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhost/jdbc/edit.html +++ /dev/null @@ -1,78 +0,0 @@ - - -
-
-
JDBC Url*:
-
- -
-
-
-
Username*:
-
- -
-
-
-
Password*:
-
- -
-
-
-
Connection Pool*:
-
- -
-
- -
-
- -
diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhost/store/pool/none/add.html b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhost/store/pool/none/add.html deleted file mode 100644 index 2666129a1f..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhost/store/pool/none/add.html +++ /dev/null @@ -1,17 +0,0 @@ - - diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/jdbc/add.html b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/jdbc/add.html deleted file mode 100644 index f9561d4c51..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/jdbc/add.html +++ /dev/null @@ -1,77 +0,0 @@ - -
-
-
JDBC Url*:
-
- -
-
-
-
Username*:
-
- -
-
-
-
Password*:
-
- -
-
-
-
Connection Pool*:
-
- -
-
- -
-
-
diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/jdbc/edit.html b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/jdbc/edit.html deleted file mode 100644 index c8cc56d1cb..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/jdbc/edit.html +++ /dev/null @@ -1,77 +0,0 @@ - -
-
-
JDBC Url*:
-
- -
-
-
-
Username*:
-
- -
-
-
-
Password*:
-
- -
-
-
-
Connection Pool*:
-
- -
-
- -
-
-
diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/jdbc/show.html b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/jdbc/show.html deleted file mode 100644 index b6145f59b6..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/jdbc/show.html +++ /dev/null @@ -1,34 +0,0 @@ - -
-
-
Connection URL:
-
-
-
-
Username:
-
-
-
-
Connection Pool Type:
-
-
-
- -
-
- diff --git a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/store/pool/none/add.html b/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/store/pool/none/add.html deleted file mode 100644 index 2666129a1f..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/main/java/resources/virtualhostnode/store/pool/none/add.html +++ /dev/null @@ -1,17 +0,0 @@ - - diff --git a/qpid/java/broker-plugins/jdbc-store/src/test/java/org/apache/qpid/server/store/jdbc/JDBCDetailsTest.java b/qpid/java/broker-plugins/jdbc-store/src/test/java/org/apache/qpid/server/store/jdbc/JDBCDetailsTest.java deleted file mode 100644 index 67e9960ca7..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/test/java/org/apache/qpid/server/store/jdbc/JDBCDetailsTest.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.store.jdbc; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import junit.framework.TestCase; - -public class JDBCDetailsTest extends TestCase -{ - public void testDerby() - { - JDBCDetails derbyDetails = JDBCDetails.getDetailsForJdbcUrl("jdbc:derby:sample", - Collections.emptyMap()); - assertEquals("derby", derbyDetails.getVendor()); - assertEquals("varchar(%d) for bit data", derbyDetails.getVarBinaryType()); - assertEquals("bigint", derbyDetails.getBigintType()); - assertEquals("blob", derbyDetails.getBlobType()); - assertFalse(derbyDetails.isUseBytesMethodsForBlob()); - - assertTrue(derbyDetails.isKnownVendor()); - assertFalse(derbyDetails.isOverridden()); - } - - public void testUnknownVendor_UsesFallbackDetails() - { - JDBCDetails details = JDBCDetails.getDetailsForJdbcUrl("jdbc:homedb:", Collections.emptyMap()); - assertEquals("fallback", details.getVendor()); - assertEquals("varchar(%d) for bit data", details.getVarBinaryType()); - assertEquals("bigint", details.getBigintType()); - assertEquals("blob", details.getBlobType()); - assertEquals(false, details.isUseBytesMethodsForBlob()); - assertFalse(details.isOverridden()); - assertFalse(details.isKnownVendor()); - } - - public void testDerbyWithOverride() - { - - Map contextMap = new HashMap<>(); - contextMap.put(JDBCDetails.CONTEXT_JDBCSTORE_VARBINARYTYPE, "myvarbin"); - - JDBCDetails derbyDetails = JDBCDetails.getDetailsForJdbcUrl("jdbc:derby:sample", contextMap); - assertEquals("derby", derbyDetails.getVendor()); - assertEquals("myvarbin", derbyDetails.getVarBinaryType()); - assertEquals("bigint", derbyDetails.getBigintType()); - assertEquals("blob", derbyDetails.getBlobType()); - assertFalse(derbyDetails.isUseBytesMethodsForBlob()); - - assertTrue(derbyDetails.isKnownVendor()); - assertTrue(derbyDetails.isOverridden()); - } - - - - - public void testRecognisedDriver_AllDetailsProvidedByContext() - { - Map contextMap = new HashMap<>(); - contextMap.put(JDBCDetails.CONTEXT_JDBCSTORE_VARBINARYTYPE, "myvarbin"); - contextMap.put(JDBCDetails.CONTEXT_JDBCSTORE_BIGINTTYPE, "mybigint"); - contextMap.put(JDBCDetails.CONTEXT_JDBCSTORE_BLOBTYPE, "myblob"); - contextMap.put(JDBCDetails.CONTEXT_JDBCSTORE_USEBYTESFORBLOB, "true"); - - JDBCDetails details = JDBCDetails.getDetailsForJdbcUrl("jdbc:sybase:", contextMap); - assertEquals("sybase", details.getVendor()); - assertEquals("myvarbin", details.getVarBinaryType()); - assertEquals("mybigint", details.getBigintType()); - assertEquals("myblob", details.getBlobType()); - assertEquals(true, details.isUseBytesMethodsForBlob()); - assertTrue(details.isKnownVendor()); - assertTrue(details.isOverridden()); - } - -} \ No newline at end of file diff --git a/qpid/java/broker-plugins/jdbc-store/src/test/java/org/apache/qpid/server/store/jdbc/JDBCMessageStoreTest.java b/qpid/java/broker-plugins/jdbc-store/src/test/java/org/apache/qpid/server/store/jdbc/JDBCMessageStoreTest.java deleted file mode 100644 index 3a85ae3257..0000000000 --- a/qpid/java/broker-plugins/jdbc-store/src/test/java/org/apache/qpid/server/store/jdbc/JDBCMessageStoreTest.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.store.jdbc; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.HashSet; -import java.util.Set; - -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.MessageStoreTestCase; -import org.apache.qpid.server.virtualhost.jdbc.JDBCVirtualHost; - -public class JDBCMessageStoreTest extends MessageStoreTestCase -{ - private String _connectionURL; - - @Override - public void tearDown() throws Exception - { - try - { - shutdownDerby(); - } - finally - { - super.tearDown(); - } - } - - public void testOnDelete() throws Exception - { - Set expectedTables = GenericJDBCMessageStore.MESSAGE_STORE_TABLE_NAMES; - assertTablesExist(expectedTables, true); - getStore().closeMessageStore(); - assertTablesExist(expectedTables, true); - getStore().onDelete(mock(JDBCVirtualHost.class)); - assertTablesExist(expectedTables, false); - } - - @Override - protected VirtualHost createVirtualHost() - { - _connectionURL = "jdbc:derby:memory:/" + getTestName() + ";create=true"; - - final JDBCVirtualHost jdbcVirtualHost = mock(JDBCVirtualHost.class); - when(jdbcVirtualHost.getConnectionUrl()).thenReturn(_connectionURL); - when(jdbcVirtualHost.getUsername()).thenReturn("test"); - when(jdbcVirtualHost.getPassword()).thenReturn("pass"); - return jdbcVirtualHost; - } - - - @Override - protected MessageStore createMessageStore() - { - return new GenericJDBCMessageStore(); - } - - private void assertTablesExist(Set expectedTables, boolean exists) throws SQLException - { - Set existingTables = getTableNames(); - for (String tableName : expectedTables) - { - assertEquals("Table " + tableName + (exists ? " is not found" : " actually exist"), exists, - existingTables.contains(tableName)); - } - } - - private Set getTableNames() throws SQLException - { - Set tableNames = new HashSet(); - Connection conn = null; - try - { - conn = openConnection(); - DatabaseMetaData metaData = conn.getMetaData(); - ResultSet tables = metaData.getTables(null, null, null, new String[] { "TABLE" }); - try - { - while (tables.next()) - { - tableNames.add(tables.getString("TABLE_NAME")); - } - } - finally - { - tables.close(); - } - } - finally - { - if (conn != null) - { - conn.close(); - } - } - return tableNames; - } - - private Connection openConnection() throws SQLException - { - return DriverManager.getConnection(_connectionURL); - } - - - private void shutdownDerby() throws SQLException - { - Connection connection = null; - try - { - connection = DriverManager.getConnection("jdbc:derby:memory:/" + getTestName() + ";shutdown=true"); - } - catch(SQLException e) - { - if (e.getSQLState().equalsIgnoreCase("08006")) - { - //expected and represents a clean shutdown of this database only, do nothing. - } - else - { - throw e; - } - } - finally - { - if (connection != null) - { - connection.close(); - } - } - } -} diff --git a/qpid/java/broker-plugins/management-amqp/pom.xml b/qpid/java/broker-plugins/management-amqp/pom.xml deleted file mode 100644 index 9540560000..0000000000 --- a/qpid/java/broker-plugins/management-amqp/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - 4.0.0 - - - qpid-java-build - org.apache.qpid - 0.32-SNAPSHOT - ../../pom.xml - - - qpid-broker-plugins-management-amqp - Qpid AMQP Management Protocol Broker Plug-in - Qpid AMQP Management broker plug-in - - - - org.apache.qpid - qpid-broker-core - ${project.version} - provided - - - - - org.apache.qpid - qpid-broker-codegen - ${project.version} - true - - - - - - - - diff --git a/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagedEntityType.java b/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagedEntityType.java deleted file mode 100644 index 10a16faa56..0000000000 --- a/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagedEntityType.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.management.amqp; - -import java.util.Arrays; - -class ManagedEntityType -{ - private final String _name; - private final ManagedEntityType[] _parents; - private final String[] _attributes; - private final String[] _operations; - - ManagedEntityType(final String name, - final ManagedEntityType[] parents, - final String[] attributes, - final String[] operations) - { - _name = name; - _parents = parents; - _attributes = attributes; - _operations = operations; - } - - public String getName() - { - return _name; - } - - public ManagedEntityType[] getParents() - { - return _parents; - } - - public String[] getAttributes() - { - return _attributes; - } - - public String[] getOperations() - { - return _operations; - } - - @Override - public String toString() - { - return "ManagedEntityType{" + - "name='" + _name + '\'' + - ", parents=" + Arrays.toString(_parents) + - ", attributes=" + Arrays.toString(_attributes) + - ", operations=" + Arrays.toString(_operations) + - '}'; - } -} diff --git a/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementNode.java b/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementNode.java deleted file mode 100644 index 8e64757cbb..0000000000 --- a/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementNode.java +++ /dev/null @@ -1,1449 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.amqp; - -import java.nio.charset.Charset; -import java.security.AccessControlException; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -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.CopyOnWriteArrayList; - -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.consumer.ConsumerTarget; -import org.apache.qpid.server.filter.FilterManager; -import org.apache.qpid.server.filter.Filterable; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.MessageDestination; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.server.message.MessageSource; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.message.internal.InternalMessage; -import org.apache.qpid.server.message.internal.InternalMessageHeader; -import org.apache.qpid.server.model.ConfigurationChangeListener; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.ManagedObject; -import org.apache.qpid.server.model.State; -import org.apache.qpid.server.plugin.MessageConverter; -import org.apache.qpid.server.plugin.SystemNodeCreator; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.protocol.MessageConverterRegistry; -import org.apache.qpid.server.store.MessageDurability; -import org.apache.qpid.server.store.MessageEnqueueRecord; -import org.apache.qpid.server.store.StorableMessageMetaData; -import org.apache.qpid.server.store.TransactionLogResource; -import org.apache.qpid.server.txn.AutoCommitTransaction; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.server.util.StateChangeListener; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; - -class ManagementNode implements MessageSource, MessageDestination -{ - - public static final String NAME_ATTRIBUTE = "name"; - public static final String IDENTITY_ATTRIBUTE = "identity"; - public static final String TYPE_ATTRIBUTE = "type"; - public static final String OPERATION_HEADER = "operation"; - public static final String SELF_NODE_NAME = "self"; - public static final String MANAGEMENT_TYPE = "org.amqp.management"; - public static final String GET_TYPES = "GET-TYPES"; - public static final String GET_ATTRIBUTES = "GET-ATTRIBUTES"; - public static final String GET_OPERATIONS = "GET-OPERATIONS"; - public static final String QUERY = "QUERY"; - public static final String ENTITY_TYPE_HEADER = "entityType"; - public static final String STATUS_CODE_HEADER = "statusCode"; - public static final int STATUS_CODE_OK = 200; - public static final String ATTRIBUTES_HEADER = "attributes"; - public static final String OFFSET_HEADER = "offset"; - public static final String COUNT_HEADER = "count"; - public static final String MANAGEMENT_NODE_NAME = "$management"; - public static final String CREATE_OPERATION = "CREATE"; - public static final String READ_OPERATION = "READ"; - public static final String UPDATE_OPERATION = "UPDATE"; - public static final String DELETE_OPERATION = "DELETE"; - public static final String STATUS_DESCRIPTION_HEADER = "statusDescription"; - public static final int NOT_FOUND_STATUS_CODE = 404; - public static final int NOT_IMPLEMENTED_STATUS_CODE = 501; - public static final int STATUS_CODE_NO_CONTENT = 204; - public static final int STATUS_CODE_FORBIDDEN = 403; - public static final int STATUS_CODE_BAD_REQUEST = 400; - public static final int STATUS_CODE_INTERNAL_ERROR = 500; - public static final String ATTRIBUTE_NAMES = "attributeNames"; - public static final String RESULTS = "results"; - - - private final VirtualHostImpl _virtualHost; - - private final UUID _id; - - private final CopyOnWriteArrayList> _consumerRegistrationListeners = - new CopyOnWriteArrayList>(); - - private final SystemNodeCreator.SystemNodeRegistry _registry; - private final ConfiguredObject _managedObject; - private Map _consumers = new ConcurrentHashMap(); - - private Map _entityTypes = Collections.synchronizedMap(new LinkedHashMap()); - - private Map> _entities = Collections.synchronizedMap(new LinkedHashMap>()); - - - public ManagementNode(final SystemNodeCreator.SystemNodeRegistry registry, - final ConfiguredObject configuredObject) - { - _virtualHost = registry.getVirtualHost(); - _registry = registry; - final String name = configuredObject.getId() + MANAGEMENT_NODE_NAME; - _id = UUID.nameUUIDFromBytes(name.getBytes(Charset.defaultCharset())); - - - _managedObject = configuredObject; - - configuredObject.addChangeListener(new ModelObjectListener()); - - } - - private Class getManagementClass(Class objectClass) - { - - if(objectClass.getAnnotation(ManagedObject.class)!=null) - { - return objectClass; - } - List allClasses = Collections.singletonList(objectClass); - List testedClasses = new ArrayList(); - do - { - testedClasses.addAll( allClasses ); - allClasses = new ArrayList(); - for(Class c : testedClasses) - { - for(Class i : c.getInterfaces()) - { - if(!allClasses.contains(i)) - { - allClasses.add(i); - } - } - if(c.getSuperclass() != null && !allClasses.contains(c.getSuperclass())) - { - allClasses.add(c.getSuperclass()); - } - } - allClasses.removeAll(testedClasses); - for(Class c : allClasses) - { - if(c.getAnnotation(ManagedObject.class) != null) - { - return c; - } - } - } - while(!allClasses.isEmpty()); - return null; - } - - private boolean populateTypeMetaData(final Class objectClass, boolean allowCreate) - { - Class clazz = getManagementClass(objectClass); - if( clazz != null) - { - ManagedObject annotation = (ManagedObject) clazz.getAnnotation(ManagedObject.class); - populateTypeMetaData(clazz, annotation); - return true; - } - else - { - return false; - } - } - - private ManagedEntityType populateTypeMetaData(Class clazz, - final ManagedObject entityType) - { - - ManagedEntityType managedEntityType = _entityTypes.get(clazz.getName()); - - if(managedEntityType == null) - { - List opsList = new ArrayList(Arrays.asList(entityType.operations())); - if(entityType.creatable()) - { - boolean isCreatableChild = false; - Collection> parentTypes = _managedObject.getModel().getParentTypes(clazz); - for(Class parentConfig : parentTypes) - { - isCreatableChild = parentConfig.isAssignableFrom(_managedObject.getClass()); - if(isCreatableChild) - { - opsList.add(CREATE_OPERATION); - break; - } - } - } - opsList.addAll(Arrays.asList(READ_OPERATION, UPDATE_OPERATION, DELETE_OPERATION)); - - Set parentSet = new HashSet(); - - List allClasses = new ArrayList(Arrays.asList(clazz.getInterfaces())); - if(clazz.getSuperclass() != null) - { - allClasses.add(clazz.getSuperclass()); - } - - for(Class parentClazz : allClasses) - { - if(parentClazz.getAnnotation(ManagedObject.class) != null) - { - ManagedEntityType parentType = populateTypeMetaData(parentClazz, - (ManagedObject) parentClazz.getAnnotation( - ManagedObject.class) - ); - parentSet.add(parentType); - parentSet.addAll(Arrays.asList(parentType.getParents())); - - } - } - managedEntityType = new ManagedEntityType(clazz.getName(), parentSet.toArray(new ManagedEntityType[parentSet.size()]), - (String[])(_managedObject.getModel().getTypeRegistry().getAttributeNames( - clazz).toArray(new String[0])), - opsList.toArray(new String[opsList.size()])); - _entityTypes.put(clazz.getName(),managedEntityType); - _entities.put(managedEntityType, Collections.synchronizedMap(new LinkedHashMap())); - - if(ConfiguredObject.class.isAssignableFrom(clazz)) - { - Collection> childTypes = _managedObject.getModel().getChildTypes(clazz); - for(Class childClass : childTypes) - { - populateTypeMetaData(childClass, true); - } - } - - } - - return managedEntityType; - - } - - @Override - public > int send(final M message, - final String routingAddress, - final InstanceProperties instanceProperties, - final ServerTransaction txn, - final Action postEnqueueAction) - { - - @SuppressWarnings("unchecked") - MessageConverter converter = - MessageConverterRegistry.getConverter(message.getClass(), InternalMessage.class); - - final InternalMessage msg = (InternalMessage) converter.convert(message, _virtualHost); - - if(validateMessage(msg)) - { - txn.addPostTransactionAction(new ServerTransaction.Action() - { - @Override - public void postCommit() - { - enqueue(msg, instanceProperties, postEnqueueAction); - } - - @Override - public void onRollback() - { - - } - }); - - return 1; - } - else - { - return 0; - } - } - - private boolean validateMessage(final ServerMessage message) - { - AMQMessageHeader header = message.getMessageHeader(); - return containsStringHeader(header, TYPE_ATTRIBUTE) && containsStringHeader(header, OPERATION_HEADER) - && (containsStringHeader(header, NAME_ATTRIBUTE) || containsStringHeader(header, IDENTITY_ATTRIBUTE)); - } - - private boolean containsStringHeader(final AMQMessageHeader header, String name) - { - return header.containsHeader(name) && header.getHeader(name) instanceof String; - } - - synchronized void enqueue(InternalMessage message, InstanceProperties properties, Action postEnqueueAction) - { - if(postEnqueueAction != null) - { - postEnqueueAction.performAction(new ConsumedMessageInstance(message, properties)); - } - - - - String name = (String) message.getMessageHeader().getHeader(NAME_ATTRIBUTE); - String id = (String) message.getMessageHeader().getHeader(IDENTITY_ATTRIBUTE); - String type = (String) message.getMessageHeader().getHeader(TYPE_ATTRIBUTE); - String operation = (String) message.getMessageHeader().getHeader(OPERATION_HEADER); - - InternalMessage response; - - if(SELF_NODE_NAME.equals(name) && type.equals(MANAGEMENT_TYPE)) - { - response = performManagementOperation(message); - } - else if(CREATE_OPERATION.equals(operation)) - { - response = performCreateOperation(message, type); - } - else - { - - ConfiguredObject entity = findSubject(name, id, type); - - if(entity != null) - { - response = performOperation(message, entity); - } - else - { - if(id != null) - { - response = createFailureResponse(message, - NOT_FOUND_STATUS_CODE, - "No entity with id {0} of type {1} found", id, type); - } - else - { - response = createFailureResponse(message, - NOT_FOUND_STATUS_CODE, - "No entity with name {0} of type {1} found", name, type); - } - } - } - - - ManagementNodeConsumer consumer = _consumers.get(message.getMessageHeader().getReplyTo()); - response.setInitialRoutingAddress(message.getMessageHeader().getReplyTo()); - if(consumer != null) - { - // TODO - check same owner - consumer.send(response); - } - else - { - _virtualHost.getDefaultDestination().send(response, - message.getMessageHeader().getReplyTo(), InstanceProperties.EMPTY, - new AutoCommitTransaction(_virtualHost.getMessageStore()), - null); - } - // TODO - route to a queue - - } - - private InternalMessage performCreateOperation(final InternalMessage message, final String type) - { - InternalMessage response; - ManagedEntityType entityType = _entityTypes.get(type); - if(type != null) - { - if(Arrays.asList(entityType.getOperations()).contains(CREATE_OPERATION)) - { - Object messageBody = message.getMessageBody(); - if(messageBody instanceof Map) - { - try - { - - Class clazz = - (Class) Class.forName(type); - try - { - ConfiguredObject child = _managedObject.createChild(clazz, (Map) messageBody); - if(child == null) - { - child = _entities.get(entityType).get(message.getMessageHeader().getHeader(NAME_ATTRIBUTE)); - } - response = performReadOperation(message, child); - } - catch(AccessControlException e) - { - response = createFailureResponse(message, STATUS_CODE_FORBIDDEN, e.getMessage()); - } - } - catch (ClassNotFoundException e) - { - response = createFailureResponse(message, - STATUS_CODE_INTERNAL_ERROR, "Unable to instantiate an instance of {0} ", type); - } - } - else - { - response = createFailureResponse(message, - STATUS_CODE_BAD_REQUEST, - "The message body in the request was not of the correct type"); - } - } - else - { - response = createFailureResponse(message, - STATUS_CODE_FORBIDDEN, - "Cannot CREATE entities of type {0}", type); - } - } - else - { - response = createFailureResponse(message, - NOT_FOUND_STATUS_CODE, - "Unknown type {0}",type); - } - return response; - } - - private InternalMessage performOperation(final InternalMessage requestMessage, final ConfiguredObject entity) - { - String operation = (String) requestMessage.getMessageHeader().getHeader(OPERATION_HEADER); - - if(READ_OPERATION.equals(operation)) - { - return performReadOperation(requestMessage, entity); - } - else if(DELETE_OPERATION.equals(operation)) - { - return performDeleteOperation(requestMessage, entity); - } - else if(UPDATE_OPERATION.equals(operation)) - { - return performUpdateOperation(requestMessage, entity); - } - else - { - return createFailureResponse(requestMessage, NOT_IMPLEMENTED_STATUS_CODE, "Unable to perform the {0} operation",operation); - } - } - - private InternalMessage performReadOperation(final InternalMessage requestMessage, final ConfiguredObject entity) - { - final InternalMessageHeader requestHeader = requestMessage.getMessageHeader(); - final MutableMessageHeader responseHeader = new MutableMessageHeader(); - responseHeader.setCorrelationId(requestHeader.getCorrelationId() == null - ? requestHeader.getMessageId() - : requestHeader.getCorrelationId()); - responseHeader.setMessageId(UUID.randomUUID().toString()); - responseHeader.setHeader(NAME_ATTRIBUTE, entity.getName()); - responseHeader.setHeader(IDENTITY_ATTRIBUTE, entity.getId().toString()); - responseHeader.setHeader(STATUS_CODE_HEADER,STATUS_CODE_OK); - final String type = getManagementClass(entity.getClass()).getName(); - responseHeader.setHeader(TYPE_ATTRIBUTE, type); - - Map responseBody = new LinkedHashMap(); - final ManagedEntityType entityType = _entityTypes.get(type); - for(String attribute : entityType.getAttributes()) - { - responseBody.put(attribute, fixValue(entity.getAttribute(attribute))); - } - - return InternalMessage.createMapMessage(_virtualHost.getMessageStore(),responseHeader, responseBody); - } - - - private InternalMessage performDeleteOperation(final InternalMessage requestMessage, final ConfiguredObject entity) - { - final InternalMessageHeader requestHeader = requestMessage.getMessageHeader(); - final MutableMessageHeader responseHeader = new MutableMessageHeader(); - responseHeader.setCorrelationId(requestHeader.getCorrelationId() == null - ? requestHeader.getMessageId() - : requestHeader.getCorrelationId()); - responseHeader.setMessageId(UUID.randomUUID().toString()); - responseHeader.setHeader(NAME_ATTRIBUTE, entity.getName()); - responseHeader.setHeader(IDENTITY_ATTRIBUTE, entity.getId().toString()); - final String type = getManagementClass(entity.getClass()).getName(); - responseHeader.setHeader(TYPE_ATTRIBUTE, type); - try - { - entity.delete(); - responseHeader.setHeader(STATUS_CODE_HEADER, STATUS_CODE_NO_CONTENT); - } - catch(AccessControlException e) - { - responseHeader.setHeader(STATUS_CODE_HEADER, STATUS_CODE_FORBIDDEN); - } - - return InternalMessage.createMapMessage(_virtualHost.getMessageStore(),responseHeader, Collections.emptyMap()); - } - - - private InternalMessage performUpdateOperation(final InternalMessage requestMessage, final ConfiguredObject entity) - { - final InternalMessageHeader requestHeader = requestMessage.getMessageHeader(); - final MutableMessageHeader responseHeader = new MutableMessageHeader(); - responseHeader.setCorrelationId(requestHeader.getCorrelationId() == null - ? requestHeader.getMessageId() - : requestHeader.getCorrelationId()); - responseHeader.setMessageId(UUID.randomUUID().toString()); - responseHeader.setHeader(NAME_ATTRIBUTE, entity.getName()); - responseHeader.setHeader(IDENTITY_ATTRIBUTE, entity.getId().toString()); - final String type = getManagementClass(entity.getClass()).getName(); - responseHeader.setHeader(TYPE_ATTRIBUTE, type); - - Object messageBody = requestMessage.getMessageBody(); - if(messageBody instanceof Map) - { - try - { - entity.setAttributes((Map)messageBody); - return performReadOperation(requestMessage, entity); - } - catch(AccessControlException e) - { - return createFailureResponse(requestMessage, STATUS_CODE_FORBIDDEN, e.getMessage()); - } - } - else - { - return createFailureResponse(requestMessage, - STATUS_CODE_BAD_REQUEST, - "The message body in the request was not of the correct type"); - } - - - } - - private ConfiguredObject findSubject(final String name, final String id, final String type) - { - ConfiguredObject subject; - ManagedEntityType met = _entityTypes.get(type); - if(met == null) - { - return null; - } - - subject = findSubject(name, id, met); - if(subject == null) - { - ArrayList allTypes = new ArrayList(_entityTypes.values()); - for(ManagedEntityType entityType : allTypes) - { - if(Arrays.asList(entityType.getParents()).contains(met)) - { - subject = findSubject(name, id, entityType); - if(subject != null) - { - return subject; - } - } - } - } - return subject; - } - - private ConfiguredObject findSubject(final String name, final String id, final ManagedEntityType entityType) - { - - Map objects = _entities.get(entityType); - if(name != null) - { - ConfiguredObject subject = objects.get(name); - if(subject != null) - { - return subject; - } - } - else - { - final Collection values = new ArrayList(objects.values()); - for(ConfiguredObject o : values) - { - if(o.getId().toString().equals(id)) - { - return o; - } - } - } - return null; - } - - private InternalMessage createFailureResponse(final InternalMessage requestMessage, - final int statusCode, - final String stateDescription, - String... params) - { - final InternalMessageHeader requestHeader = requestMessage.getMessageHeader(); - final MutableMessageHeader responseHeader = new MutableMessageHeader(); - responseHeader.setCorrelationId(requestHeader.getCorrelationId() == null - ? requestHeader.getMessageId() - : requestHeader.getCorrelationId()); - responseHeader.setMessageId(UUID.randomUUID().toString()); - for(String header : requestHeader.getHeaderNames()) - { - responseHeader.setHeader(header, requestHeader.getHeader(header)); - } - responseHeader.setHeader(STATUS_CODE_HEADER, statusCode); - responseHeader.setHeader(STATUS_DESCRIPTION_HEADER, MessageFormat.format(stateDescription, params)); - return InternalMessage.createBytesMessage(_virtualHost.getMessageStore(), responseHeader, new byte[0]); - - } - - private InternalMessage performManagementOperation(final InternalMessage msg) - { - final InternalMessage responseMessage; - final InternalMessageHeader requestHeader = msg.getMessageHeader(); - final MutableMessageHeader responseHeader = new MutableMessageHeader(); - responseHeader.setCorrelationId(requestHeader.getCorrelationId() == null - ? requestHeader.getMessageId() - : requestHeader.getCorrelationId()); - responseHeader.setMessageId(UUID.randomUUID().toString()); - - - String operation = (String) requestHeader.getHeader(OPERATION_HEADER); - if(GET_TYPES.equals(operation)) - { - responseMessage = performGetTypes(requestHeader, responseHeader); - } - else if(GET_ATTRIBUTES.equals(operation)) - { - responseMessage = performGetAttributes(requestHeader, responseHeader); - } - else if(GET_OPERATIONS.equals(operation)) - { - responseMessage = performGetOperations(requestHeader, responseHeader); - } - else if(QUERY.equals(operation)) - { - responseMessage = performQuery(requestHeader, msg.getMessageBody(), responseHeader); - } - else - { - responseMessage = InternalMessage.createBytesMessage(_virtualHost.getMessageStore(), requestHeader, new byte[0]); - } - return responseMessage; - } - - private InternalMessage performGetTypes(final InternalMessageHeader requestHeader, - final MutableMessageHeader responseHeader) - { - final InternalMessage responseMessage; - List restriction; - if(requestHeader.containsHeader(ENTITY_TYPE_HEADER)) - { - restriction = new ArrayList(Collections.singletonList( (String)requestHeader.getHeader(ENTITY_TYPE_HEADER))); - } - else - { - restriction = null; - } - - responseHeader.setHeader(STATUS_CODE_HEADER, STATUS_CODE_OK); - Map responseMap = new LinkedHashMap(); - Map entityMapCopy; - synchronized (_entityTypes) - { - entityMapCopy = new LinkedHashMap(_entityTypes); - } - - for(ManagedEntityType type : entityMapCopy.values()) - { - if(restriction == null || meetsIndirectRestriction(type,restriction)) - { - final ManagedEntityType[] parents = type.getParents(); - List parentNames = new ArrayList(); - if(parents != null) - { - for(ManagedEntityType parent : parents) - { - parentNames.add(parent.getName()); - } - } - responseMap.put(type.getName(), parentNames); - } - } - responseMessage = InternalMessage.createMapMessage(_virtualHost.getMessageStore(), responseHeader, responseMap); - return responseMessage; - } - - private InternalMessage performGetAttributes(final InternalMessageHeader requestHeader, - final MutableMessageHeader responseHeader) - { - final InternalMessage responseMessage; - String restriction; - if(requestHeader.containsHeader(ENTITY_TYPE_HEADER)) - { - restriction = (String) requestHeader.getHeader(ENTITY_TYPE_HEADER); - } - else - { - restriction = null; - } - - responseHeader.setHeader(STATUS_CODE_HEADER, STATUS_CODE_OK); - Map responseMap = new LinkedHashMap(); - Map entityMapCopy; - synchronized (_entityTypes) - { - entityMapCopy = new LinkedHashMap(_entityTypes); - } - - if(restriction == null) - { - for(ManagedEntityType type : entityMapCopy.values()) - { - responseMap.put(type.getName(), Arrays.asList(type.getAttributes())); - } - } - else if(entityMapCopy.containsKey(restriction)) - { - responseMap.put(restriction, Arrays.asList(entityMapCopy.get(restriction).getAttributes())); - } - - responseMessage = InternalMessage.createMapMessage(_virtualHost.getMessageStore(), responseHeader, responseMap); - return responseMessage; - } - - - private InternalMessage performGetOperations(final InternalMessageHeader requestHeader, - final MutableMessageHeader responseHeader) - { - final InternalMessage responseMessage; - String restriction; - if(requestHeader.containsHeader(ENTITY_TYPE_HEADER)) - { - restriction = (String) requestHeader.getHeader(ENTITY_TYPE_HEADER); - } - else - { - restriction = null; - } - - responseHeader.setHeader(STATUS_CODE_HEADER, STATUS_CODE_OK); - Map responseMap = new LinkedHashMap(); - Map entityMapCopy; - synchronized (_entityTypes) - { - entityMapCopy = new LinkedHashMap(_entityTypes); - } - - if(restriction == null) - { - for(ManagedEntityType type : entityMapCopy.values()) - { - responseMap.put(type.getName(), Arrays.asList(type.getOperations())); - } - } - else if(entityMapCopy.containsKey(restriction)) - { - ManagedEntityType type = entityMapCopy.get(restriction); - responseMap.put(type.getName(), Arrays.asList(type.getOperations())); - } - responseMessage = InternalMessage.createMapMessage(_virtualHost.getMessageStore(), responseHeader, responseMap); - return responseMessage; - } - - private InternalMessage performQuery(final InternalMessageHeader requestHeader, - final Object messageBody, final MutableMessageHeader responseHeader) - { - final InternalMessage responseMessage; - List restriction; - List attributes; - int offset; - int count; - - if(requestHeader.containsHeader(ENTITY_TYPE_HEADER)) - { - restriction = new ArrayList(Collections.singletonList((String) requestHeader.getHeader( - ENTITY_TYPE_HEADER))); - responseHeader.setHeader(ENTITY_TYPE_HEADER, restriction); - } - else - { - restriction = new ArrayList(_entityTypes.keySet()); - } - - - if(messageBody instanceof Map && ((Map)messageBody).get(ATTRIBUTE_NAMES) instanceof List) - { - attributes = (List) ((Map)messageBody).get(ATTRIBUTE_NAMES); - } - else - { - LinkedHashMap attributeSet = new LinkedHashMap(); - for(String entityType : restriction) - { - ManagedEntityType type = _entityTypes.get(entityType); - if(type != null) - { - for(String attributeName : type.getAttributes()) - { - attributeSet.put(attributeName, null); - } - } - } - attributes = new ArrayList(attributeSet.keySet()); - - } - - if(requestHeader.containsHeader(OFFSET_HEADER)) - { - offset = ((Number) requestHeader.getHeader(OFFSET_HEADER)).intValue(); - responseHeader.setHeader(OFFSET_HEADER,offset); - } - else - { - offset = 0; - } - - if(requestHeader.containsHeader(COUNT_HEADER)) - { - count = ((Number) requestHeader.getHeader(COUNT_HEADER)).intValue(); - } - else - { - count = Integer.MAX_VALUE; - } - - - responseHeader.setHeader(STATUS_CODE_HEADER, STATUS_CODE_OK); - List> responseList = new ArrayList>(); - int rowNo = 0; - for(String type : restriction) - { - ManagedEntityType entityType = _entityTypes.get(type); - if(entityType != null) - { - Map entityMap = _entities.get(entityType); - if(entityMap != null) - { - List entities; - synchronized(entityMap) - { - entities = new ArrayList(entityMap.values()); - } - for(ConfiguredObject entity : entities) - { - if(rowNo++ >= offset) - { - Object[] attrValue = new Object[attributes.size()]; - int col = 0; - for(String attr : attributes) - { - Object value; - if(TYPE_ATTRIBUTE.equals(attr)) - { - value = entityType.getName(); - } - else - { - value = fixValue(entity.getAttribute(attr)); - } - attrValue[col++] = value; - } - responseList.add(Arrays.asList(attrValue)); - } - if(responseList.size()==count+1) - { - break; - } - } - } - } - - if(responseList.size()==count) - { - break; - } - } - responseHeader.setHeader(COUNT_HEADER, responseList.size()); - Map responseMap = new HashMap(); - responseMap.put(ATTRIBUTE_NAMES, attributes); - responseMap.put(RESULTS, responseList); - responseMessage = InternalMessage.createMapMessage(_virtualHost.getMessageStore(), - responseHeader, - responseMap); - return responseMessage; - } - - private Object fixValue(final Object value) - { - Object fixedValue; - if(value instanceof Enum) - { - fixedValue = value.toString(); - } - else if(value instanceof Map) - { - Map oldValue = (Map) value; - Map newValue = new LinkedHashMap(); - for(Map.Entry entry : oldValue.entrySet()) - { - newValue.put(fixValue(entry.getKey()),fixValue(entry.getValue())); - } - fixedValue = newValue; - } - else if(value instanceof Collection) - { - Collection oldValue = (Collection) value; - List newValue = new ArrayList(oldValue.size()); - for(Object o : oldValue) - { - newValue.add(fixValue(o)); - } - fixedValue = newValue; - } - else if(value != null && value.getClass().isArray() && !(value instanceof byte[])) - { - fixedValue = fixValue(Arrays.asList((Object[])value)); - } - else - { - fixedValue = value; - } - return fixedValue; - - } - - - private boolean meetsIndirectRestriction(final ManagedEntityType type, final List restriction) - { - if(restriction.contains(type.getName())) - { - return true; - } - if(type.getParents() != null) - { - for(ManagedEntityType parent : type.getParents()) - { - if(meetsIndirectRestriction(parent, restriction)) - { - return true; - } - } - } - return false; - } - - @Override - public synchronized ManagementNodeConsumer addConsumer(final ConsumerTarget target, - final FilterManager filters, - final Class messageClass, - final String consumerName, - final EnumSet options) - { - - final ManagementNodeConsumer managementNodeConsumer = new ManagementNodeConsumer(consumerName,this, target); - target.consumerAdded(managementNodeConsumer); - _consumers.put(consumerName, managementNodeConsumer); - for(ConsumerRegistrationListener listener : _consumerRegistrationListeners) - { - listener.consumerAdded(this, managementNodeConsumer); - } - return managementNodeConsumer; - } - - @Override - public synchronized Collection getConsumers() - { - return new ArrayList(_consumers.values()); - } - - @Override - public void addConsumerRegistrationListener(final ConsumerRegistrationListener listener) - { - _consumerRegistrationListeners.add(listener); - } - - @Override - public void removeConsumerRegistrationListener(final ConsumerRegistrationListener listener) - { - _consumerRegistrationListeners.remove(listener); - } - - @Override - public boolean verifySessionAccess(final AMQSessionModel session) - { - return true; - } - - @Override - public String getName() - { - return MANAGEMENT_NODE_NAME; - } - - @Override - public UUID getId() - { - return _id; - } - - @Override - public MessageDurability getMessageDurability() - { - return MessageDurability.NEVER; - } - - private class ConsumedMessageInstance implements MessageInstance - { - private final ServerMessage _message; - private final InstanceProperties _properties; - - public ConsumedMessageInstance(final ServerMessage message, - final InstanceProperties properties) - { - _message = message; - _properties = properties; - } - - @Override - public int getDeliveryCount() - { - return 0; - } - - @Override - public void incrementDeliveryCount() - { - - } - - @Override - public void decrementDeliveryCount() - { - - } - - @Override - public void addStateChangeListener(final StateChangeListener listener) - { - - } - - @Override - public boolean removeStateChangeListener(final StateChangeListener listener) - { - return false; - } - - - @Override - public boolean acquiredByConsumer() - { - return false; - } - - @Override - public ConsumerImpl getAcquiringConsumer() - { - return null; - } - - @Override - public MessageEnqueueRecord getEnqueueRecord() - { - return null; - } - - @Override - public boolean isAcquiredBy(final ConsumerImpl consumer) - { - return false; - } - - @Override - public boolean removeAcquisitionFromConsumer(final ConsumerImpl consumer) - { - return false; - } - - @Override - public void setRedelivered() - { - - } - - @Override - public boolean isRedelivered() - { - return false; - } - - @Override - public ConsumerImpl getDeliveredConsumer() - { - return null; - } - - @Override - public void reject() - { - - } - - @Override - public boolean isRejectedBy(final ConsumerImpl consumer) - { - return false; - } - - @Override - public boolean getDeliveredToConsumer() - { - return true; - } - - @Override - public boolean expired() - { - return false; - } - - @Override - public boolean acquire(final ConsumerImpl sub) - { - return false; - } - - @Override - public boolean lockAcquisition() - { - return false; - } - - @Override - public boolean unlockAcquisition() - { - return false; - } - - @Override - public int getMaximumDeliveryCount() - { - return 0; - } - - @Override - public int routeToAlternate(final Action action, - final ServerTransaction txn) - { - return 0; - } - - - @Override - public Filterable asFilterable() - { - return null; - } - - @Override - public boolean isAvailable() - { - return false; - } - - @Override - public boolean acquire() - { - return false; - } - - @Override - public boolean isAcquired() - { - return false; - } - - @Override - public void release() - { - - } - - @Override - public boolean resend() - { - return false; - } - - @Override - public void delete() - { - - } - - @Override - public boolean isDeleted() - { - return false; - } - - @Override - public ServerMessage getMessage() - { - return _message; - } - - @Override - public InstanceProperties getInstanceProperties() - { - return _properties; - } - - @Override - public TransactionLogResource getOwningResource() - { - return ManagementNode.this; - } - } - - private class ModelObjectListener implements ConfigurationChangeListener - { - @Override - public void stateChanged(final ConfiguredObject object, final State oldState, final State newState) - { - if(newState == State.DELETED) - { - _registry.removeSystemNode(ManagementNode.this); - } - else if(newState == State.ACTIVE && object instanceof org.apache.qpid.server.model.VirtualHost) - { - populateTypeMetaData(object.getClass(), false); - final Class managementClass = getManagementClass(_managedObject.getClass()); - _entities.get(_entityTypes.get(managementClass.getName())).put(_managedObject.getName(), _managedObject); - - Collection> childClasses = object.getModel().getChildTypes(managementClass); - for(Class childClass : childClasses) - { - if(getManagementClass(childClass) != null) - { - for(ConfiguredObject child : _managedObject.getChildren(childClass)) - { - _entities.get(_entityTypes.get(getManagementClass(childClass).getName())).put(child.getName(), child); - } - } - } - - } - } - - @Override - public void childAdded(final ConfiguredObject object, final ConfiguredObject child) - { - final Class managementClass = getManagementClass(child.getClass()); - final ManagedEntityType entityType = _entityTypes.get(managementClass.getName()); - if(entityType != null) - { - _entities.get(entityType).put(child.getName(), child); - } - } - - @Override - public void childRemoved(final ConfiguredObject object, final ConfiguredObject child) - { - final ManagedEntityType entityType = _entityTypes.get(getManagementClass(child.getClass()).getName()); - if(entityType != null) - { - _entities.get(entityType).remove(child.getName()); - } - } - - @Override - public void attributeSet(final ConfiguredObject object, - final String attributeName, - final Object oldAttributeValue, - final Object newAttributeValue) - { - - } - } - - private static class MutableMessageHeader implements AMQMessageHeader - { - private final LinkedHashMap _headers = new LinkedHashMap(); - private String _correlationId; - private long _expiration; - private String _userId; - private String _appId; - private String _messageId; - private String _mimeType; - private String _encoding; - private byte _priority; - private long _timestamp; - private String _type; - private String _replyTo; - - public void setCorrelationId(final String correlationId) - { - _correlationId = correlationId; - } - - public void setExpiration(final long expiration) - { - _expiration = expiration; - } - - public void setUserId(final String userId) - { - _userId = userId; - } - - public void setAppId(final String appId) - { - _appId = appId; - } - - public void setMessageId(final String messageId) - { - _messageId = messageId; - } - - public void setMimeType(final String mimeType) - { - _mimeType = mimeType; - } - - public void setEncoding(final String encoding) - { - _encoding = encoding; - } - - public void setPriority(final byte priority) - { - _priority = priority; - } - - public void setTimestamp(final long timestamp) - { - _timestamp = timestamp; - } - - public void setType(final String type) - { - _type = type; - } - - public void setReplyTo(final String replyTo) - { - _replyTo = replyTo; - } - - public String getCorrelationId() - { - return _correlationId; - } - - public long getExpiration() - { - return _expiration; - } - - public String getUserId() - { - return _userId; - } - - public String getAppId() - { - return _appId; - } - - public String getMessageId() - { - return _messageId; - } - - public String getMimeType() - { - return _mimeType; - } - - public String getEncoding() - { - return _encoding; - } - - public byte getPriority() - { - return _priority; - } - - public long getTimestamp() - { - return _timestamp; - } - - public String getType() - { - return _type; - } - - public String getReplyTo() - { - return _replyTo; - } - - @Override - public Object getHeader(final String name) - { - return _headers.get(name); - } - - @Override - public boolean containsHeaders(final Set names) - { - return _headers.keySet().containsAll(names); - } - - @Override - public boolean containsHeader(final String name) - { - return _headers.containsKey(name); - } - - @Override - public Collection getHeaderNames() - { - return Collections.unmodifiableCollection(_headers.keySet()); - } - - public void setHeader(String header, Object value) - { - _headers.put(header,value); - } - - } -} diff --git a/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementNodeConsumer.java b/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementNodeConsumer.java deleted file mode 100644 index 28d8a6c88c..0000000000 --- a/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementNodeConsumer.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.qpid.server.management.amqp; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; - -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.consumer.ConsumerTarget; -import org.apache.qpid.server.message.MessageSource; -import org.apache.qpid.server.message.internal.InternalMessage; -import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.util.StateChangeListener; - -class ManagementNodeConsumer implements ConsumerImpl -{ - private final long _id = ConsumerImpl.CONSUMER_NUMBER_GENERATOR.getAndIncrement(); - private final ManagementNode _managementNode; - private final List _queue = Collections.synchronizedList(new ArrayList()); - private final ConsumerTarget _target; - private final String _name; - private final StateChangeListener _targetChangeListener = new TargetChangeListener(); - - - public ManagementNodeConsumer(final String consumerName, final ManagementNode managementNode, ConsumerTarget target) - { - _name = consumerName; - _managementNode = managementNode; - _target = target; - target.addStateListener(_targetChangeListener); - } - - @Override - public void externalStateChange() - { - - } - - @Override - public long getBytesOut() - { - return 0; - } - - @Override - public long getMessagesOut() - { - return 0; - } - - @Override - public long getUnacknowledgedBytes() - { - return 0; - } - - @Override - public long getUnacknowledgedMessages() - { - return 0; - } - - @Override - public AMQSessionModel getSessionModel() - { - return _target.getSessionModel(); - } - - @Override - public MessageSource getMessageSource() - { - return _managementNode; - } - - @Override - public long getConsumerNumber() - { - return _id; - } - - @Override - public boolean isSuspended() - { - return false; - } - - @Override - public boolean isClosed() - { - return false; - } - - @Override - public boolean acquires() - { - return true; - } - - @Override - public boolean seesRequeues() - { - return false; - } - - @Override - public void close() - { - } - - @Override - public boolean trySendLock() - { - return _target.trySendLock(); - } - - @Override - public void getSendLock() - { - _target.getSendLock(); - } - - @Override - public void releaseSendLock() - { - _target.releaseSendLock(); - } - - - @Override - public boolean isActive() - { - return false; - } - - @Override - public String getName() - { - return _name; - } - - @Override - public void flush() - { - - } - - @Override - public ConsumerTarget getTarget() - { - return _target; - } - - ManagementNode getManagementNode() - { - return _managementNode; - } - - void send(final InternalMessage response) - { - _target.getSendLock(); - try - { - final ManagementResponse responseEntry = new ManagementResponse(this, response); - if(_queue.isEmpty() && _target.allocateCredit(response)) - { - _target.send(this, responseEntry, false); - } - else - { - _queue.add(responseEntry); - } - } - finally - { - _target.releaseSendLock(); - } - } - - private class TargetChangeListener implements StateChangeListener - { - @Override - public void stateChanged(final ConsumerTarget object, - final ConsumerTarget.State oldState, - final ConsumerTarget.State newState) - { - if(newState == ConsumerTarget.State.ACTIVE) - { - deliverMessages(); - } - } - } - - private void deliverMessages() - { - _target.getSendLock(); - try - { - while(!_queue.isEmpty()) - { - - final ManagementResponse managementResponse = _queue.get(0); - if(!_target.isSuspended() && _target.allocateCredit(managementResponse.getMessage())) - { - _queue.remove(0); - _target.send(this, managementResponse, false); - } - else - { - break; - } - } - } - finally - { - _target.releaseSendLock(); - } - } -} diff --git a/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementNodeCreator.java b/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementNodeCreator.java deleted file mode 100644 index e977c027a1..0000000000 --- a/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementNodeCreator.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.management.amqp; - -import org.apache.qpid.server.plugin.PluggableService; -import org.apache.qpid.server.plugin.SystemNodeCreator; - -@PluggableService -public class ManagementNodeCreator implements SystemNodeCreator -{ - @Override - public void register(final SystemNodeRegistry registry) - { - ManagementNode managementNode = new ManagementNode(registry,registry.getVirtualHost()); - registry.registerSystemNode(managementNode); - } - - @Override - public String getType() - { - return "AMQP-VIRTUALHOST-MANAGEMENT"; - } -} diff --git a/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementResponse.java b/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementResponse.java deleted file mode 100644 index dd5b7540a7..0000000000 --- a/qpid/java/broker-plugins/management-amqp/src/main/java/org/apache/qpid/server/management/amqp/ManagementResponse.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.amqp; - -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.filter.Filterable; -import org.apache.qpid.server.message.InstanceProperties; -import org.apache.qpid.server.message.MessageInstance; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.message.internal.InternalMessage; -import org.apache.qpid.server.store.MessageEnqueueRecord; -import org.apache.qpid.server.store.TransactionLogResource; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.util.Action; -import org.apache.qpid.server.util.StateChangeListener; - -class ManagementResponse implements MessageInstance -{ - private final ManagementNodeConsumer _consumer; - private int _deliveryCount; - private boolean _isRedelivered; - private boolean _isDelivered; - private boolean _isDeleted; - private InternalMessage _message; - - ManagementResponse(final ManagementNodeConsumer consumer, final InternalMessage message) - { - _consumer = consumer; - _message = message; - } - - @Override - public int getDeliveryCount() - { - return 0; - } - - @Override - public void incrementDeliveryCount() - { - _deliveryCount++; - } - - @Override - public void decrementDeliveryCount() - { - _deliveryCount--; - } - - @Override - public void addStateChangeListener(final StateChangeListener listener) - { - - } - - @Override - public boolean removeStateChangeListener(final StateChangeListener listener) - { - return false; - } - - - @Override - public boolean acquiredByConsumer() - { - return !isDeleted(); - } - - @Override - public ConsumerImpl getAcquiringConsumer() - { - return _consumer; - } - - @Override - public MessageEnqueueRecord getEnqueueRecord() - { - return null; - } - - @Override - public boolean isAcquiredBy(final ConsumerImpl consumer) - { - return consumer == _consumer && !isDeleted(); - } - - @Override - public boolean removeAcquisitionFromConsumer(final ConsumerImpl consumer) - { - return consumer == _consumer; - } - - @Override - public void setRedelivered() - { - _isRedelivered = true; - } - - @Override - public boolean isRedelivered() - { - return _isRedelivered; - } - - @Override - public ManagementNodeConsumer getDeliveredConsumer() - { - return isDeleted() ? null : _consumer; - } - - @Override - public void reject() - { - delete(); - } - - @Override - public boolean isRejectedBy(final ConsumerImpl consumer) - { - return false; - } - - @Override - public boolean getDeliveredToConsumer() - { - return _isDelivered; - } - - @Override - public boolean expired() - { - return false; - } - - @Override - public boolean acquire(final ConsumerImpl sub) - { - return false; - } - - @Override - public boolean lockAcquisition() - { - return false; - } - - @Override - public boolean unlockAcquisition() - { - return false; - } - - @Override - public int getMaximumDeliveryCount() - { - return 0; - } - - @Override - public int routeToAlternate(final Action action, - final ServerTransaction txn) - { - return 0; - } - - - @Override - public Filterable asFilterable() - { - return null; - } - - @Override - public boolean isAvailable() - { - return false; - } - - @Override - public boolean acquire() - { - return false; - } - - @Override - public boolean isAcquired() - { - return !isDeleted(); - } - - @Override - public void release() - { - delete(); - } - - @Override - public boolean resend() - { - return false; - } - - @Override - public void delete() - { - _isDeleted = true; - } - - @Override - public boolean isDeleted() - { - return _isDeleted; - } - - @Override - public ServerMessage getMessage() - { - return _message; - } - - @Override - public InstanceProperties getInstanceProperties() - { - return InstanceProperties.EMPTY; - } - - @Override - public TransactionLogResource getOwningResource() - { - return _consumer.getManagementNode(); - } -} diff --git a/qpid/java/broker-plugins/management-http/pom.xml b/qpid/java/broker-plugins/management-http/pom.xml deleted file mode 100644 index 50ff3e20f3..0000000000 --- a/qpid/java/broker-plugins/management-http/pom.xml +++ /dev/null @@ -1,140 +0,0 @@ - - - - 4.0.0 - - - org.apache.qpid - qpid-java-build - 0.32-SNAPSHOT - ../../pom.xml - - - qpid-broker-plugins-management-http - Qpid HTTP Management Broker Plug-in - HTTP Management broker plug-in - - - 1.10.3 - - - - - org.apache.qpid - qpid-broker-core - ${project.version} - provided - - - - org.apache.qpid - qpid-broker-codegen - ${project.version} - true - - - - log4j - log4j - ${log4j-version} - - - - org.slf4j - slf4j-api - ${slf4j-version} - - - - org.apache.geronimo.specs - geronimo-servlet_3.0_spec - ${geronimo-servlet-version} - - - - org.eclipse.jetty - jetty-server - ${jetty-version} - - - org.eclipse.jetty.orbit - javax.servlet - - - - - - org.eclipse.jetty - jetty-servlet - ${jetty-version} - - - - org.dojotoolkit - dojo - ${dojo-version} - distribution - zip - - - - - org.apache.qpid - qpid-test-utils - ${project.version} - test - - - - - - - src/main/resources - - - src/main/java - - resources/ - - - - src/main/resources-maven - true - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - - - dojo-${dojo-version}-distribution.zip - - - - - - - - diff --git a/qpid/java/broker-plugins/management-http/src/main/appended-resources/META-INF/LICENSE.vm b/qpid/java/broker-plugins/management-http/src/main/appended-resources/META-INF/LICENSE.vm deleted file mode 100644 index 7a7430e2e3..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/appended-resources/META-INF/LICENSE.vm +++ /dev/null @@ -1,33 +0,0 @@ - - -#============================================== -# Third Party Dependency Licensing Information: -#============================================== - -resources/js/crypto-js/ - -This bundles portions of crypto-js, which is under the MIT licence: - - -Copyright (c) 2009-2013 Jeff Mott - - 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, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - 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. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -#=============================================== diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/DojoHelper.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/DojoHelper.java deleted file mode 100644 index 31a777d0bb..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/DojoHelper.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.management.plugin; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Map; -import java.util.Properties; - -public class DojoHelper -{ - private static final Logger _logger = LoggerFactory.getLogger(DojoHelper.class); - - public static final String VERSION_FILE = "dojoconfig.properties"; - public static final String DOJO_VERSION_PROPERTY = "dojo-version"; - public static final String DOJO_PATH_PROPERTY = "dojo-path"; - public static final String DIJIT_PATH_PROPERTY = "dijit-path"; - public static final String DOJOX_PATH_PROPERTY = "dojox-path"; - - private static String _version = "undefined"; - private static String _dojoPath = "/dojo-undefined/dojo"; - private static String _dijitPath = "/dojo-undefined/dijit"; - private static String _dojoxPath = "/dojo-undefined/dojox"; - - // Loads the value from the properties file. - static - { - Properties props = new Properties(); - - try - { - InputStream propertyStream = DojoHelper.class.getClassLoader().getResourceAsStream(VERSION_FILE); - if (propertyStream == null) - { - _logger.warn("Unable to find resource " + VERSION_FILE + " from classloader"); - } - else - { - try - { - props.load(propertyStream); - } - finally - { - try - { - propertyStream.close(); - } - catch (IOException e) - { - _logger.warn("Exception closing InputStream for " + VERSION_FILE + " resource:", e); - } - } - - if (_logger.isDebugEnabled()) - { - _logger.debug("Dumping Dojo Config:"); - for (Map.Entry entry : props.entrySet()) - { - _logger.debug("Property: " + entry.getKey() + " Value: " + entry.getValue()); - } - - _logger.debug("End of property dump"); - } - - _version = props.getProperty(DOJO_VERSION_PROPERTY, _version); - _dojoPath = props.getProperty(DOJO_PATH_PROPERTY, _dojoPath); - _dijitPath = props.getProperty(DIJIT_PATH_PROPERTY, _dijitPath); - _dojoxPath = props.getProperty(DOJOX_PATH_PROPERTY, _dojoxPath); - } - } - catch (IOException e) - { - // Log a warning about this and leave the values initialized to unknown. - _logger.error("Exception loading " + VERSION_FILE + " resource:", e); - } - } - - public static String getDojoVersion() - { - return _version; - } - - public static String getDojoPath() - { - return _dojoPath; - } - - public static String getDijitPath() - { - return _dijitPath; - } - - public static String getDojoxPath() - { - return _dojoxPath; - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagement.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagement.java deleted file mode 100644 index fbe9f068b9..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagement.java +++ /dev/null @@ -1,613 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.plugin; - -import java.io.IOException; -import java.io.Writer; -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.net.ssl.KeyManager; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; -import javax.servlet.DispatcherType; -import javax.servlet.MultipartConfigElement; -import javax.servlet.http.HttpServletRequest; - -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import org.eclipse.jetty.io.EndPoint; -import org.eclipse.jetty.server.Connector; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.SessionManager; -import org.eclipse.jetty.server.handler.ErrorHandler; -import org.eclipse.jetty.server.nio.SelectChannelConnector; -import org.eclipse.jetty.server.ssl.SslSelectChannelConnector; -import org.eclipse.jetty.servlet.FilterHolder; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.logging.messages.ManagementConsoleMessages; -import org.apache.qpid.server.management.plugin.connector.TcpAndSslSelectChannelConnector; -import org.apache.qpid.server.management.plugin.filter.ForbiddingAuthorisationFilter; -import org.apache.qpid.server.management.plugin.filter.ForbiddingTraceFilter; -import org.apache.qpid.server.management.plugin.filter.RedirectingAuthorisationFilter; -import org.apache.qpid.server.management.plugin.servlet.DefinedFileServlet; -import org.apache.qpid.server.management.plugin.servlet.FileServlet; -import org.apache.qpid.server.management.plugin.servlet.LogFileServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.ApiDocsServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.HelperServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.LogFileListingServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.LogRecordsServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.LoggedOnUserPreferencesServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.LogoutServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.MessageContentServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.MessageServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.MetaDataServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.QueueReportServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.RestServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.SaslServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.StructureServlet; -import org.apache.qpid.server.management.plugin.servlet.rest.UserPreferencesServlet; -import org.apache.qpid.server.model.*; -import org.apache.qpid.server.model.adapter.AbstractPluginAdapter; -import org.apache.qpid.server.model.port.HttpPort; -import org.apache.qpid.server.model.port.PortManager; -import org.apache.qpid.server.util.ServerScopedRuntimeException; -import org.apache.qpid.transport.network.security.ssl.QpidMultipleTrustManager; -import org.apache.qpid.transport.network.security.ssl.SSLUtil; - -@ManagedObject( category = false, type = "MANAGEMENT-HTTP" ) -public class HttpManagement extends AbstractPluginAdapter implements HttpManagementConfiguration, PortManager -{ - private static final String PORT_SERVLET_ATTRIBUTE = "org.apache.qpid.server.model.Port"; - private final Logger _logger = LoggerFactory.getLogger(HttpManagement.class); - - // 10 minutes by default - public static final int DEFAULT_TIMEOUT_IN_SECONDS = 60 * 10; - public static final String TIME_OUT = "sessionTimeout"; - public static final String HTTP_BASIC_AUTHENTICATION_ENABLED = "httpBasicAuthenticationEnabled"; - public static final String HTTPS_BASIC_AUTHENTICATION_ENABLED = "httpsBasicAuthenticationEnabled"; - public static final String HTTP_SASL_AUTHENTICATION_ENABLED = "httpSaslAuthenticationEnabled"; - public static final String HTTPS_SASL_AUTHENTICATION_ENABLED = "httpsSaslAuthenticationEnabled"; - - public static final String PLUGIN_TYPE = "MANAGEMENT-HTTP"; - - private static final String OPERATIONAL_LOGGING_NAME = "Web"; - - private static final String JSESSIONID_COOKIE_PREFIX = "JSESSIONID_"; - - private Server _server; - - @ManagedAttributeField - private boolean _httpsSaslAuthenticationEnabled; - - @ManagedAttributeField - private boolean _httpSaslAuthenticationEnabled; - - @ManagedAttributeField - private boolean _httpsBasicAuthenticationEnabled; - - @ManagedAttributeField - private boolean _httpBasicAuthenticationEnabled; - - @ManagedAttributeField - private int _sessionTimeout; - - @ManagedAttributeField - private boolean _compressResponses; - - private boolean _allowPortActivation; - - @ManagedObjectFactoryConstructor - public HttpManagement(Map attributes, Broker broker) - { - super(attributes, broker); - } - - @StateTransition(currentState = {State.UNINITIALIZED,State.ERRORED}, desiredState = State.ACTIVE) - private ListenableFuture doStart() - { - getBroker().getEventLogger().message(ManagementConsoleMessages.STARTUP(OPERATIONAL_LOGGING_NAME)); - - Collection> httpPorts = getHttpPorts(getBroker().getPorts()); - _server = createServer(httpPorts); - try - { - _server.start(); - logOperationalListenMessages(httpPorts); - } - catch (Exception e) - { - throw new ServerScopedRuntimeException("Failed to start HTTP management on ports : " + httpPorts, e); - } - - getBroker().getEventLogger().message(ManagementConsoleMessages.READY(OPERATIONAL_LOGGING_NAME)); - setState(State.ACTIVE); - return Futures.immediateFuture(null); - } - - @Override - protected void onClose() - { - if (_server != null) - { - try - { - _server.stop(); - logOperationalShutdownMessage(_server); - } - catch (Exception e) - { - throw new ServerScopedRuntimeException("Failed to stop HTTP management on ports : " + getHttpPorts(getBroker().getPorts()), e); - } - } - - getBroker().getEventLogger().message(ManagementConsoleMessages.STOPPED(OPERATIONAL_LOGGING_NAME)); - } - - public int getSessionTimeout() - { - return _sessionTimeout; - } - - private Server createServer(Collection> ports) - { - if (_logger.isInfoEnabled()) - { - _logger.info("Starting up web server on " + ports); - } - _allowPortActivation = true; - - Server server = new Server(); - - QueuedThreadPool threadPool = new QueuedThreadPool(); - threadPool.setName("HttpManagement"); - threadPool.setMaxQueued(getContextValue(Integer.class, JETTY_THREAD_POOL_MAX_QUEUED)); - threadPool.setMaxThreads(getContextValue(Integer.class, JETTY_THREAD_POOL_MAX_THREADS)); - threadPool.setMinThreads(getContextValue(Integer.class, JETTY_THREAD_POOL_MIN_THREADS)); - - server.setThreadPool(threadPool); - - int lastPort = -1; - for (Port port : ports) - { - if(port instanceof HttpPort) - { - - if (!State.ACTIVE.equals(port.getDesiredState())) - { - continue; - } - ((HttpPort)port).setPortManager(this); - - if(port.getState() != State.ACTIVE) - { - - // TODO - RG - probably does nothing - port.startAsync(); - } - Connector connector = null; - - Collection transports = port.getTransports(); - if (!transports.contains(Transport.SSL)) - { - final Port thePort = port; - connector = new SelectChannelConnector() - { - @Override - public void customize(final EndPoint endpoint, final Request request) throws IOException - { - super.customize(endpoint, request); - request.setAttribute(PORT_SERVLET_ATTRIBUTE, thePort); - } - }; - } - else if (transports.contains(Transport.SSL)) - { - connector = createSslConnector((HttpPort) port); - } - else - { - throw new IllegalArgumentException("Unexpected transport on port " - + port.getName() - + ":" - + transports); - } - lastPort = port.getPort(); - String bindingAddress = ((HttpPort)port).getBindingAddress(); - if (bindingAddress != null && !bindingAddress.trim().equals("") && !bindingAddress.trim().equals("*")) - { - connector.setHost(bindingAddress.trim()); - } - connector.setPort(port.getPort()); - server.addConnector(connector); - } - else - { - throw new IllegalArgumentException("Http management can only be added to an Http port"); - } - - } - - _allowPortActivation = false; - - ServletContextHandler root = new ServletContextHandler(ServletContextHandler.SESSIONS); - root.setContextPath("/"); - root.setCompactPath(true); - server.setHandler(root); - server.setSendServerVersion(false); - final ErrorHandler errorHandler = new ErrorHandler() - { - @Override - protected void writeErrorPageBody(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks) - throws IOException - { - String uri= request.getRequestURI(); - - writeErrorPageMessage(request,writer,code,message,uri); - - for (int i= 0; i < 20; i++) - writer.write("
\n"); - } - }; - root.setErrorHandler(errorHandler); - - // set servlet context attributes for broker and configuration - root.getServletContext().setAttribute(HttpManagementUtil.ATTR_BROKER, getBroker()); - root.getServletContext().setAttribute(HttpManagementUtil.ATTR_MANAGEMENT_CONFIGURATION, this); - - root.addFilter(new FilterHolder(new ForbiddingTraceFilter()), "/*", EnumSet.of(DispatcherType.REQUEST)); - FilterHolder restAuthorizationFilter = new FilterHolder(new ForbiddingAuthorisationFilter()); - restAuthorizationFilter.setInitParameter(ForbiddingAuthorisationFilter.INIT_PARAM_ALLOWED, "/service/sasl"); - root.addFilter(restAuthorizationFilter, "/api/*", EnumSet.of(DispatcherType.REQUEST)); - root.addFilter(restAuthorizationFilter, "/apidocs/*", EnumSet.of(DispatcherType.REQUEST)); - root.addFilter(restAuthorizationFilter, "/service/*", EnumSet.of(DispatcherType.REQUEST)); - root.addFilter(new FilterHolder(new RedirectingAuthorisationFilter()), HttpManagementUtil.ENTRY_POINT_PATH, EnumSet.of(DispatcherType.REQUEST)); - root.addFilter(new FilterHolder(new RedirectingAuthorisationFilter()), "/index.html", EnumSet.of(DispatcherType.REQUEST)); - root.addFilter(new FilterHolder(new RedirectingAuthorisationFilter()), "/", EnumSet.of(DispatcherType.REQUEST)); - - addRestServlet(root, "broker"); - addRestServlet(root, "virtualhostnode", VirtualHostNode.class); - addRestServlet(root, "authenticationprovider", AuthenticationProvider.class); - addRestServlet(root, "accesscontrolprovider", AccessControlProvider.class); - addRestServlet(root, "user", AuthenticationProvider.class, User.class); - addRestServlet(root, "groupprovider", GroupProvider.class); - addRestServlet(root, "group", GroupProvider.class, Group.class); - addRestServlet(root, "groupmember", GroupProvider.class, Group.class, GroupMember.class); - addRestServlet(root, "port", Port.class); - addRestServlet(root, "keystore", KeyStore.class); - addRestServlet(root, "truststore", TrustStore.class); - addRestServlet(root, "plugin", Plugin.class); - addRestServlet(root, "preferencesprovider", AuthenticationProvider.class, PreferencesProvider.class); - - addRestServlet(root, "replicationnode", VirtualHostNode.class, RemoteReplicationNode.class); - - addRestServlet(root, "virtualhost", VirtualHostNode.class, VirtualHost.class); - addRestServlet(root, "exchange", VirtualHostNode.class, VirtualHost.class, Exchange.class); - addRestServlet(root, "queue", VirtualHostNode.class, VirtualHost.class, Queue.class); - addRestServlet(root, "connection", VirtualHostNode.class, VirtualHost.class, Connection.class); - addRestServlet(root, "binding", VirtualHostNode.class, VirtualHost.class, Exchange.class, Queue.class, Binding.class); - addRestServlet(root, "session", VirtualHostNode.class, VirtualHost.class, Connection.class, Session.class); - - ServletHolder apiDocsServlet = new ServletHolder(new ApiDocsServlet(getModel(), Collections.emptyList())); - root.addServlet(apiDocsServlet, "/apidocs"); - root.addServlet(apiDocsServlet, "/apidocs/"); - root.addServlet(apiDocsServlet, "/apidocs/latest"); - root.addServlet(apiDocsServlet, "/apidocs/latest/"); - root.addServlet(new ServletHolder(new UserPreferencesServlet()), "/service/userpreferences/*"); - root.addServlet(new ServletHolder(new LoggedOnUserPreferencesServlet()), "/service/preferences"); - root.addServlet(new ServletHolder(new StructureServlet()), "/service/structure"); - root.addServlet(new ServletHolder(new MessageServlet()), "/service/message/*"); - root.addServlet(new ServletHolder(new MessageContentServlet()), "/service/message-content/*"); - root.addServlet(new ServletHolder(new QueueReportServlet()), "/service/queuereport/*"); - - - root.addServlet(new ServletHolder(new LogRecordsServlet()), "/service/logrecords"); - - root.addServlet(new ServletHolder(new MetaDataServlet(getModel())), "/service/metadata"); - - root.addServlet(new ServletHolder(new SaslServlet()), "/service/sasl"); - - root.addServlet(new ServletHolder(new DefinedFileServlet("index.html")), HttpManagementUtil.ENTRY_POINT_PATH); - root.addServlet(new ServletHolder(new DefinedFileServlet("index.html")), "/"); - root.addServlet(new ServletHolder(new LogoutServlet()), "/logout"); - - root.addServlet(new ServletHolder(new FileServlet(DojoHelper.getDojoPath(), true)), "/dojo/dojo/*"); - root.addServlet(new ServletHolder(new FileServlet(DojoHelper.getDijitPath(), true)), "/dojo/dijit/*"); - root.addServlet(new ServletHolder(new FileServlet(DojoHelper.getDojoxPath(), true)), "/dojo/dojox/*"); - - root.addServlet(new ServletHolder(new FileServlet()), "*.js"); - root.addServlet(new ServletHolder(new FileServlet()), "*.css"); - root.addServlet(new ServletHolder(new FileServlet()), "*.html"); - root.addServlet(new ServletHolder(new FileServlet()), "*.png"); - root.addServlet(new ServletHolder(new FileServlet()), "*.gif"); - root.addServlet(new ServletHolder(new FileServlet()), "*.jpg"); - root.addServlet(new ServletHolder(new FileServlet()), "*.jpeg"); - root.addServlet(new ServletHolder(new FileServlet()), "*.json"); - root.addServlet(new ServletHolder(new FileServlet()), "*.txt"); - root.addServlet(new ServletHolder(new FileServlet()), "*.xsl"); - root.addServlet(new ServletHolder(new HelperServlet()), "/service/helper"); - root.addServlet(new ServletHolder(new LogFileListingServlet()), "/service/logfilenames"); - root.addServlet(new ServletHolder(new LogFileServlet()), "/service/logfile"); - - final SessionManager sessionManager = root.getSessionHandler().getSessionManager(); - sessionManager.getSessionCookieConfig().setName(JSESSIONID_COOKIE_PREFIX + lastPort); - sessionManager.setMaxInactiveInterval((Integer)getAttribute(TIME_OUT)); - - return server; - } - - private Connector createSslConnector(final HttpPort port) - { - final Connector connector; - KeyStore keyStore = port.getKeyStore(); - Collection trustStores = port.getTrustStores(); - if (keyStore == null) - { - throw new IllegalConfigurationException("Key store is not configured. Cannot start management on HTTPS port without keystore"); - } - SslContextFactory factory = new SslContextFactory(); - factory.addExcludeProtocols(SSLUtil.SSLV3_PROTOCOL); - - if(port.getDisabledCipherSuites() != null) - { - factory.addExcludeCipherSuites(port.getDisabledCipherSuites().toArray(new String[port.getDisabledCipherSuites().size()])); - } - - if(port.getEnabledCipherSuites() != null && !port.getEnabledCipherSuites().isEmpty()) - { - factory.setIncludeCipherSuites(port.getEnabledCipherSuites().toArray(new String[port.getEnabledCipherSuites().size()])); - } - - boolean needClientCert = port.getNeedClientAuth() || port.getWantClientAuth(); - - if (needClientCert && trustStores.isEmpty()) - { - throw new IllegalConfigurationException("Client certificate authentication is enabled on AMQP port '" - + this.getName() + "' but no trust store defined"); - } - - try - { - SSLContext sslContext = SSLContext.getInstance("TLS"); - KeyManager[] keyManagers = keyStore.getKeyManagers(); - - TrustManager[] trustManagers; - if(trustStores == null || trustStores.isEmpty()) - { - trustManagers = null; - } - else if(trustStores.size() == 1) - { - trustManagers = trustStores.iterator().next().getTrustManagers(); - } - else - { - Collection trustManagerList = new ArrayList<>(); - final QpidMultipleTrustManager mulTrustManager = new QpidMultipleTrustManager(); - - for(TrustStore ts : trustStores) - { - TrustManager[] managers = ts.getTrustManagers(); - if(managers != null) - { - for(TrustManager manager : managers) - { - if(manager instanceof X509TrustManager) - { - mulTrustManager.addTrustManager((X509TrustManager)manager); - } - else - { - trustManagerList.add(manager); - } - } - } - } - if(!mulTrustManager.isEmpty()) - { - trustManagerList.add(mulTrustManager); - } - trustManagers = trustManagerList.toArray(new TrustManager[trustManagerList.size()]); - } - sslContext.init(keyManagers, trustManagers, null); - - factory.setSslContext(sslContext); - if(port.getNeedClientAuth()) - { - factory.setNeedClientAuth(true); - } - else if(port.getWantClientAuth()) - { - factory.setWantClientAuth(true); - } - } - catch (GeneralSecurityException e) - { - throw new ServerScopedRuntimeException("Cannot configure port " + port.getName() + " for transport " + Transport.SSL, e); - } - connector = port.getTransports().contains(Transport.TCP) - ? new TcpAndSslSelectChannelConnector(factory) - { - @Override - public void customize(final EndPoint endpoint, final Request request) throws IOException - { - super.customize(endpoint, request); - request.setAttribute(PORT_SERVLET_ATTRIBUTE, port); - } - } - : new SslSelectChannelConnector(factory) - { - @Override - public void customize(final EndPoint endpoint, final Request request) throws IOException - { - super.customize(endpoint, request); - request.setAttribute(PORT_SERVLET_ATTRIBUTE, port); - } - }; - return connector; - } - - private void addRestServlet(ServletContextHandler root, String name, Class... hierarchy) - { - ServletHolder servletHolder = new ServletHolder(name, new RestServlet(hierarchy)); - servletHolder.getRegistration().setMultipartConfig( - new MultipartConfigElement("", - getContextValue(Long.class, MAX_HTTP_FILE_UPLOAD_SIZE_CONTEXT_NAME), - -1l, - getContextValue(Integer.class, MAX_HTTP_FILE_UPLOAD_SIZE_CONTEXT_NAME))); - - List paths = Arrays.asList("/api/latest/" + name , - "/api/v" + BrokerModel.MODEL_MAJOR_VERSION + "/" + name ); - - for(String path : paths) - { - root.addServlet(servletHolder, path + "/*"); - } - ServletHolder docServletHolder = new ServletHolder(name+"docs", new ApiDocsServlet(getModel(), - paths, - hierarchy)); - root.addServlet(docServletHolder, "/apidocs/latest/" + name + "/"); - root.addServlet(docServletHolder, "/apidocs/v" + BrokerModel.MODEL_MAJOR_VERSION + "/" + name +"/"); - root.addServlet(docServletHolder, "/apidocs/latest/" + name ); - root.addServlet(docServletHolder, "/apidocs/v" + BrokerModel.MODEL_MAJOR_VERSION + "/" + name); - - - } - - private void logOperationalListenMessages(Collection> ports) - { - for (Port port : ports) - { - Set transports = port.getTransports(); - for (Transport transport: transports) - { - getBroker().getEventLogger().message(ManagementConsoleMessages.LISTENING(Protocol.HTTP.name(), transport.name(), port.getPort())); - } - } - } - - private void logOperationalShutdownMessage(Server server) - { - Connector[] connectors = server.getConnectors(); - for (Connector connector : connectors) - { - getBroker().getEventLogger().message(ManagementConsoleMessages.SHUTTING_DOWN(Protocol.HTTP.name(), connector.getPort())); - } - } - - - private Collection> getHttpPorts(Collection> ports) - { - Collection> httpPorts = new HashSet<>(); - for (Port port : ports) - { - if (port.getProtocols().contains(Protocol.HTTP)) - { - httpPorts.add(port); - } - } - return httpPorts; - } - - @Override - public boolean isActivationAllowed(final Port port) - { - return _allowPortActivation; - } - - @Override - public boolean isHttpsSaslAuthenticationEnabled() - { - return _httpsSaslAuthenticationEnabled; - } - - @Override - public boolean isHttpSaslAuthenticationEnabled() - { - return _httpSaslAuthenticationEnabled; - } - - @Override - public boolean isHttpsBasicAuthenticationEnabled() - { - return _httpsBasicAuthenticationEnabled; - } - - @Override - public boolean isHttpBasicAuthenticationEnabled() - { - return _httpBasicAuthenticationEnabled; - } - - @Override - public boolean isCompressResponses() - { - return _compressResponses; - } - - @Override - public AuthenticationProvider getAuthenticationProvider(HttpServletRequest request) - { - HttpPort port = (HttpPort)request.getAttribute(PORT_SERVLET_ATTRIBUTE); - return port == null ? null : port.getAuthenticationProvider(); - } - - @Override - protected void validateChange(final ConfiguredObject proxyForValidation, final Set changedAttributes) - { - super.validateChange(proxyForValidation, changedAttributes); - - HttpManagementConfiguration updated = (HttpManagementConfiguration)proxyForValidation; - if(changedAttributes.contains(HttpManagement.NAME)) - { - if(!getName().equals(updated.getName())) - { - throw new IllegalConfigurationException("Changing the name of http management plugin is not allowed"); - } - } - if (changedAttributes.contains(TIME_OUT)) - { - int value = updated.getSessionTimeout(); - if (value < 0) - { - throw new IllegalConfigurationException("Only positive integer value can be specified for the session time out attribute"); - } - } - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagementConfiguration.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagementConfiguration.java deleted file mode 100644 index d3d9770912..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagementConfiguration.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.management.plugin; - -import java.net.SocketAddress; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.ManagedAttribute; -import org.apache.qpid.server.model.ManagedContextDefault; -import org.apache.qpid.server.model.Plugin; - -public interface HttpManagementConfiguration> extends Plugin -{ - - @ManagedAttribute( defaultValue = "true" ) - boolean isHttpsSaslAuthenticationEnabled(); - - @ManagedAttribute( defaultValue = "true" ) - boolean isHttpSaslAuthenticationEnabled(); - - @ManagedAttribute( defaultValue = "true" ) - boolean isHttpsBasicAuthenticationEnabled(); - - @ManagedAttribute( defaultValue = "false" ) - boolean isHttpBasicAuthenticationEnabled(); - - @ManagedAttribute( defaultValue = "600" ) - public int getSessionTimeout(); - - String QPID_HELP_URL = "qpid.helpURL"; - @ManagedContextDefault(name = QPID_HELP_URL) - String DEFAULT_HELP_URL = "http://qpid.apache.org/releases/qpid-${qpid.version}/java-broker/book"; - - String HTTP_MANAGEMENT_COMPRESS_RESPONSES = "httpManagement.compressResponses"; - @ManagedContextDefault(name = HTTP_MANAGEMENT_COMPRESS_RESPONSES) - boolean DEFAULT_COMPRESS_RESPONSES = false; - - @ManagedAttribute( defaultValue = "${"+HTTP_MANAGEMENT_COMPRESS_RESPONSES+"}" ) - public boolean isCompressResponses(); - - String MAX_HTTP_FILE_UPLOAD_SIZE_CONTEXT_NAME = "maxHttpFileUploadSize"; - @ManagedContextDefault( name = MAX_HTTP_FILE_UPLOAD_SIZE_CONTEXT_NAME) - static final long DEFAULT_MAX_UPLOAD_SIZE = 100 * 1024; - - - String JETTY_THREAD_POOL_MAX_QUEUED = "jetty.threadPool.maxQueued"; - @ManagedContextDefault( name = JETTY_THREAD_POOL_MAX_QUEUED) - static final long DEFAULT_JETTY_THREAD_POOL_MAX_QUEUED = 1000; - - String JETTY_THREAD_POOL_MAX_THREADS = "jetty.threadPool.maxThreads"; - @ManagedContextDefault( name = JETTY_THREAD_POOL_MAX_THREADS) - static final long DEFAULT_JETTY_THREAD_POOL_MAX_THREADS = 50; - - - String JETTY_THREAD_POOL_MIN_THREADS = "jetty.threadPool.minThreads"; - @ManagedContextDefault( name = JETTY_THREAD_POOL_MIN_THREADS) - static final long DEFAULT_JETTY_THREAD_POOL_MIN_THREADS = 5; - - - - AuthenticationProvider getAuthenticationProvider(HttpServletRequest request); -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagementUtil.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagementUtil.java deleted file mode 100644 index 90906538d2..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagementUtil.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.plugin; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.security.Principal; -import java.security.PrivilegedAction; -import java.security.cert.X509Certificate; -import java.util.Collections; -import java.util.zip.GZIPOutputStream; - -import javax.security.auth.Subject; -import javax.security.auth.x500.X500Principal; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.apache.commons.codec.binary.Base64; - -import org.apache.qpid.server.management.plugin.servlet.ServletConnectionPrincipal; -import org.apache.qpid.server.management.plugin.session.LoginLogoutReporter; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.security.SubjectCreator; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; -import org.apache.qpid.server.security.auth.AuthenticationResult.AuthenticationStatus; -import org.apache.qpid.server.security.auth.SubjectAuthenticationResult; -import org.apache.qpid.server.security.auth.UsernamePrincipal; -import org.apache.qpid.server.security.auth.manager.AnonymousAuthenticationManager; -import org.apache.qpid.server.security.auth.manager.ExternalAuthenticationManager; -import org.apache.qpid.transport.network.security.ssl.SSLUtil; - -public class HttpManagementUtil -{ - - /** - * Servlet context attribute holding a reference to a broker instance - */ - public static final String ATTR_BROKER = "Qpid.broker"; - - /** - * Servlet context attribute holding a reference to plugin configuration - */ - public static final String ATTR_MANAGEMENT_CONFIGURATION = "Qpid.managementConfiguration"; - - /** - * Default management entry URL - */ - public static final String ENTRY_POINT_PATH = "/management"; - - private static final String ATTR_LOGIN_LOGOUT_REPORTER = "Qpid.loginLogoutReporter"; - private static final String ATTR_SUBJECT = "Qpid.subject"; - private static final String ATTR_LOG_ACTOR = "Qpid.logActor"; - - private static final String ACCEPT_ENCODING_HEADER = "Accept-Encoding"; - private static final String CONTENT_ENCODING_HEADER = "Content-Encoding"; - private static final String GZIP_CONTENT_ENCODING = "gzip"; - - public static Broker getBroker(ServletContext servletContext) - { - return (Broker) servletContext.getAttribute(ATTR_BROKER); - } - - public static HttpManagementConfiguration getManagementConfiguration(ServletContext servletContext) - { - return (HttpManagementConfiguration) servletContext.getAttribute(ATTR_MANAGEMENT_CONFIGURATION); - } - - public static SocketAddress getSocketAddress(HttpServletRequest request) - { - return InetSocketAddress.createUnresolved(request.getServerName(), request.getServerPort()); - } - - public static Subject getAuthorisedSubject(HttpSession session) - { - return (Subject) session.getAttribute(ATTR_SUBJECT); - } - - public static void checkRequestAuthenticatedAndAccessAuthorized(HttpServletRequest request, Broker broker, - HttpManagementConfiguration managementConfig) - { - HttpSession session = request.getSession(); - Subject subject = getAuthorisedSubject(session); - if (subject == null) - { - subject = tryToAuthenticate(request, managementConfig); - if (subject == null) - { - throw new SecurityException("Only authenticated users can access the management interface"); - } - - Subject original = subject; - subject = new Subject(false, - original.getPrincipals(), - original.getPublicCredentials(), - original.getPrivateCredentials()); - subject.getPrincipals().add(new ServletConnectionPrincipal(request)); - subject.setReadOnly(); - - assertManagementAccess(broker.getSecurityManager(), subject); - - saveAuthorisedSubject(session, subject); - - - } - } - - public static void assertManagementAccess(final SecurityManager securityManager, Subject subject) - { - Subject.doAs(subject, new PrivilegedAction() - { - @Override - public Void run() - { - securityManager.accessManagement(); - return null; - } - }); - } - - public static void saveAuthorisedSubject(HttpSession session, Subject subject) - { - session.setAttribute(ATTR_SUBJECT, subject); - - // Cause the user logon to be logged. - session.setAttribute(ATTR_LOGIN_LOGOUT_REPORTER, - new LoginLogoutReporter(subject, getBroker(session.getServletContext()))); - } - - public static Subject tryToAuthenticate(HttpServletRequest request, HttpManagementConfiguration managementConfig) - { - Subject subject = null; - final AuthenticationProvider authenticationProvider = managementConfig.getAuthenticationProvider(request); - SubjectCreator subjectCreator = authenticationProvider.getSubjectCreator(request.isSecure()); - String remoteUser = request.getRemoteUser(); - - if (remoteUser != null || authenticationProvider instanceof AnonymousAuthenticationManager) - { - subject = authenticateUser(subjectCreator, remoteUser, null); - } - else if(authenticationProvider instanceof ExternalAuthenticationManager - && Collections.list(request.getAttributeNames()).contains("javax.servlet.request.X509Certificate")) - { - Principal principal = null; - X509Certificate[] certificates = - (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate"); - if(certificates != null && certificates.length != 0) - { - principal = certificates[0].getSubjectX500Principal(); - - if(!Boolean.valueOf(String.valueOf(authenticationProvider.getAttribute(ExternalAuthenticationManager.ATTRIBUTE_USE_FULL_DN)))) - { - String username; - String dn = ((X500Principal) principal).getName(X500Principal.RFC2253); - - - username = SSLUtil.getIdFromSubjectDN(dn); - principal = new UsernamePrincipal(username); - } - - subject = subjectCreator.createSubjectWithGroups(new AuthenticatedPrincipal(principal)); - } - } - else - { - String header = request.getHeader("Authorization"); - if (header != null) - { - String[] tokens = header.split("\\s"); - if (tokens.length >= 2 && "BASIC".equalsIgnoreCase(tokens[0])) - { - boolean isBasicAuthSupported = false; - if (request.isSecure()) - { - isBasicAuthSupported = managementConfig.isHttpsBasicAuthenticationEnabled(); - } - else - { - isBasicAuthSupported = managementConfig.isHttpBasicAuthenticationEnabled(); - } - if (isBasicAuthSupported) - { - String base64UsernameAndPassword = tokens[1]; - String[] credentials = (new String(Base64.decodeBase64(base64UsernameAndPassword.getBytes()))).split(":", 2); - if (credentials.length == 2) - { - subject = authenticateUser(subjectCreator, credentials[0], credentials[1]); - } - } - } - } - } - return subject; - } - - private static Subject authenticateUser(SubjectCreator subjectCreator, String username, String password) - { - SubjectAuthenticationResult authResult = subjectCreator.authenticate(username, password); - if (authResult.getStatus() == AuthenticationStatus.SUCCESS) - { - return authResult.getSubject(); - } - return null; - } - - public static Writer getOutputWriter(final HttpServletRequest request, final HttpServletResponse response) - throws IOException - { - return getOutputWriter(request, response, getManagementConfiguration(request.getServletContext())); - } - - public static Writer getOutputWriter(final HttpServletRequest request, final HttpServletResponse response, HttpManagementConfiguration managementConfiguration) - throws IOException - { - Writer writer; - writer = new BufferedWriter(new OutputStreamWriter(getOutputStream(request,response, managementConfiguration))); - - return writer; - } - - public static OutputStream getOutputStream(final HttpServletRequest request, final HttpServletResponse response) - throws IOException - { - return getOutputStream(request, response, getManagementConfiguration(request.getServletContext())); - } - - public static OutputStream getOutputStream(final HttpServletRequest request, final HttpServletResponse response, HttpManagementConfiguration managementConfiguration) - throws IOException - { - OutputStream outputStream; - if(managementConfiguration.isCompressResponses() - && Collections.list(request.getHeaderNames()).contains(ACCEPT_ENCODING_HEADER) - && request.getHeader(ACCEPT_ENCODING_HEADER).contains(GZIP_CONTENT_ENCODING)) - { - outputStream = new GZIPOutputStream(response.getOutputStream()); - response.setHeader(CONTENT_ENCODING_HEADER, GZIP_CONTENT_ENCODING); - } - else - { - outputStream = response.getOutputStream(); - } - return outputStream; - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/connector/TcpAndSslSelectChannelConnector.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/connector/TcpAndSslSelectChannelConnector.java deleted file mode 100644 index 197032398e..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/connector/TcpAndSslSelectChannelConnector.java +++ /dev/null @@ -1,378 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.plugin.connector; - -import java.io.IOException; -import java.nio.channels.SelectionKey; -import java.nio.channels.SocketChannel; - -import javax.net.ssl.SSLEngine; -import javax.net.ssl.SSLSession; - -import org.eclipse.jetty.http.HttpSchemes; -import org.eclipse.jetty.io.AsyncEndPoint; -import org.eclipse.jetty.io.Buffer; -import org.eclipse.jetty.io.Connection; -import org.eclipse.jetty.io.EndPoint; -import org.eclipse.jetty.io.nio.AsyncConnection; -import org.eclipse.jetty.io.nio.IndirectNIOBuffer; -import org.eclipse.jetty.io.nio.SelectChannelEndPoint; -import org.eclipse.jetty.io.nio.SelectorManager; -import org.eclipse.jetty.io.nio.SslConnection; -import org.eclipse.jetty.server.AsyncHttpConnection; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.nio.SelectChannelConnector; -import org.eclipse.jetty.server.ssl.SslCertificates; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; -import org.eclipse.jetty.util.ssl.SslContextFactory; - -public class TcpAndSslSelectChannelConnector extends SelectChannelConnector -{ - - private static final Logger LOG = Log.getLogger(TcpAndSslSelectChannelConnector.class); - - private final SslContextFactory _sslContextFactory; - - public TcpAndSslSelectChannelConnector(SslContextFactory factory) - { - _sslContextFactory = factory; - addBean(_sslContextFactory); - setUseDirectBuffers(false); - setSoLingerTime(30000); - } - - - @Override - public void customize(EndPoint endpoint, Request request) throws IOException - { - if(endpoint instanceof SslConnection.SslEndPoint) - { - request.setScheme(HttpSchemes.HTTPS); - } - - super.customize(endpoint,request); - - if(endpoint instanceof SslConnection.SslEndPoint) - { - SslConnection.SslEndPoint sslEndpoint = (SslConnection.SslEndPoint) endpoint; - SSLEngine sslEngine = sslEndpoint.getSslEngine(); - SSLSession sslSession = sslEngine.getSession(); - - SslCertificates.customize(sslSession, endpoint, request); - } - } - - @Override - protected AsyncConnection newConnection(SocketChannel channel, AsyncEndPoint endpoint) - { - return new ProtocolIdentifyingConnection((ProtocolIdentifyingEndpoint) endpoint); - } - - @Override - protected SelectChannelEndPoint newEndPoint(final SocketChannel channel, - final SelectorManager.SelectSet selectSet, - final SelectionKey key) throws IOException - { - - ProtocolIdentifyingEndpoint endpoint = new ProtocolIdentifyingEndpoint(channel,selectSet,key, getMaxIdleTime()); - endpoint.setConnection(selectSet.getManager().newConnection(channel, endpoint, key.attachment())); - return endpoint; - } - - protected SSLEngine createSSLEngine(SocketChannel channel) throws IOException - { - SSLEngine engine; - if (channel != null) - { - String peerHost = channel.socket().getInetAddress().getHostAddress(); - int peerPort = channel.socket().getPort(); - engine = _sslContextFactory.newSslEngine(peerHost, peerPort); - } - else - { - engine = _sslContextFactory.newSslEngine(); - } - - engine.setUseClientMode(false); - return engine; - } - - @Override - protected void doStart() throws Exception - { - _sslContextFactory.checkKeyStore(); - _sslContextFactory.start(); - - SSLEngine sslEngine = _sslContextFactory.newSslEngine(); - - sslEngine.setUseClientMode(false); - - SSLSession sslSession = sslEngine.getSession(); - - if (getRequestHeaderSize() _appenders; - - public LogFileHelper(Collection appenders) - { - super(); - _appenders = appenders; - } - - public List findLogFileDetails(String[] requestedFiles) - { - List logFiles = new ArrayList(); - Map> cache = new HashMap>(); - for (int i = 0; i < requestedFiles.length; i++) - { - String logFile = requestedFiles[i]; - if ("".equals(logFile)) - { - throw new IllegalArgumentException("Log file parameter is empty"); - } - int pos = logFile.indexOf("/"); - if (pos == -1) - { - throw new IllegalArgumentException("Log file parameter '" + logFile + "' does not include an appender name"); - } - if (pos == logFile.length()) - { - throw new IllegalArgumentException("Log file parameter '" + logFile + "' does not include an file name"); - } - - String appenderName = logFile.substring(0, pos); - String fileName = logFile.substring(pos + 1); - - List appenderFiles = cache.get(appenderName); - if (appenderFiles == null) - { - Appender fileAppender = null; - for (Appender appender : _appenders) - { - if (appenderName.equals(appender.getName())) - { - fileAppender = appender; - break; - } - } - if (fileAppender == null) - { - continue; - } - appenderFiles = getAppenderFiles(fileAppender, true); - if (appenderFiles == null) - { - continue; - } - cache.put(appenderName, appenderFiles); - } - for (LogFileDetails logFileDetails : appenderFiles) - { - if (logFileDetails.getName().equals(fileName)) - { - logFiles.add(logFileDetails); - break; - } - } - } - return logFiles; - } - - public List getLogFileDetails(boolean includeLogFileLocation) - { - List results = new ArrayList(); - for (Appender appender : _appenders) - { - List appenderFiles = getAppenderFiles(appender, includeLogFileLocation); - if (appenderFiles != null) - { - results.addAll(appenderFiles); - } - } - return results; - } - - public void writeLogFiles(List logFiles, OutputStream os) throws IOException - { - ZipOutputStream out = new ZipOutputStream(os); - try - { - addLogFileEntries(logFiles, out); - } - finally - { - out.close(); - } - } - - public void writeLogFile(File file, OutputStream os) throws IOException - { - FileInputStream fis = new FileInputStream(file); - try - { - byte[] bytes = new byte[BUFFER_LENGTH]; - int length = 1; - while ((length = fis.read(bytes)) != -1) - { - os.write(bytes, 0, length); - } - } - finally - { - fis.close(); - } - } - - private List getAppenderFiles(Appender appender, boolean includeLogFileLocation) - { - if (appender instanceof QpidCompositeRollingAppender) - { - return listQpidCompositeRollingAppenderFiles((QpidCompositeRollingAppender) appender, includeLogFileLocation); - } - else if (appender instanceof FileAppender) - { - return listFileAppenderFiles((FileAppender) appender, includeLogFileLocation); - } - return null; - } - - private List listFileAppenderFiles(FileAppender appender, boolean includeLogFileLocation) - { - String appenderFilePath = appender.getFile(); - File appenderFile = new File(appenderFilePath); - if (appenderFile.exists()) - { - return listLogFiles(appenderFile.getParentFile(), appenderFile.getName(), appender.getName(), "", includeLogFileLocation); - } - return Collections.emptyList(); - } - - private List listQpidCompositeRollingAppenderFiles(QpidCompositeRollingAppender appender, boolean includeLogFileLocation) - { - List files = listFileAppenderFiles((FileAppender) appender, includeLogFileLocation); - String appenderFilePath = appender.getFile(); - File appenderFile = new File(appenderFilePath); - File backupFolder = new File(appender.getBackupFilesToPath()); - if (backupFolder.exists()) - { - String backupFolderName = backupFolder.getName() + "/"; - List backedUpFiles = listLogFiles(backupFolder, appenderFile.getName(), appender.getName(), - backupFolderName, includeLogFileLocation); - files.addAll(backedUpFiles); - } - return files; - } - - private List listLogFiles(File parent, String baseFileName, String appenderName, String relativePath, - boolean includeLogFileLocation) - { - List files = new ArrayList(); - for (File file : parent.listFiles()) - { - String name = file.getName(); - if (name.startsWith(baseFileName)) - { - String displayPath = name; - if (!relativePath.equals("")) - { - displayPath = relativePath + name; - } - files.add(new LogFileDetails(displayPath, appenderName, includeLogFileLocation ? file : null, getMimeType(name), file.length(), - file.lastModified())); - } - } - return files; - } - - private String getMimeType(String fileName) - { - if (fileName.endsWith(GZIP_EXTENSION)) - { - return GZIP_MIME_TYPE; - } - return TEXT_MIME_TYPE; - } - - private void addLogFileEntries(List files, ZipOutputStream out) throws IOException - { - for (LogFileDetails logFileDetails : files) - { - File file = logFileDetails.getLocation(); - if (file.exists()) - { - ZipEntry entry = new ZipEntry(logFileDetails.getAppenderName() + "/" + logFileDetails.getName()); - entry.setSize(file.length()); - out.putNextEntry(entry); - writeLogFile(file, out); - out.closeEntry(); - } - out.flush(); - } - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/QueueBinaryReport.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/QueueBinaryReport.java deleted file mode 100644 index d842de3f1b..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/QueueBinaryReport.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.management.plugin.report; - -public abstract class QueueBinaryReport extends QueueReport -{ - public QueueBinaryReport() - { - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/QueueReport.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/QueueReport.java deleted file mode 100644 index 23b24aaf8d..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/QueueReport.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.management.plugin.report; - -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.VirtualHost; - -/** - *

- * The QueueReport class provides an extension point for installations to provide custom management reporting on - * queues through the REST API. - *

- * - *

- * A custom QueueReport must extend either {@link org.apache.qpid.server.management.plugin.report.QueueTextReport} - * or {@link org.apache.qpid.server.management.plugin.report.QueueBinaryReport}. The report implementation must - * define a {@link #getName() name} which is unique amongst all installed reports. The report class must be present - * in the classpath of the broker, and a provider-configuration file named - * org.apache.qpid.server.management.plugin.report.QueueReport must be added in the resource directory - * META-INF/services directory with the binary name of the implementation (as described in - * {@link java.util.ServiceLoader ServiceLoader}). - *

- * - *

Running reports

- *

- * The report can be run using the URL: - * {@code http:///service/queuereport///[?param1=x¶m2=y...]} - *

- * - *

Report Parameters

- * - *

- * Reports can take parameters from the query string of the HTTP request. For every parameter in the query string - * the system will look for a setter on the report object with either a String or String[] parameter. Thus if - * the query string contains {@code foo=bar}, then the system will look for a setter {@code setFoo(String value)} or - * {@code setFoo(String[] value)}. If the same parameter occurs multiple times in the query string then only the - * array variant of the setter will be called. - *

- *

- * Setters for the parameters are guaranteed to be called before the first message is added to the report. - *

- * - *

- * NOTE: In order to comply with the requirements of the {@link java.util.ServiceLoader ServiceLoader} api, all - * implementations of QueueReport MUST provide a public no-args constructor. - *

- * @param - */ -public abstract class QueueReport -{ - private Queue _queue; - - QueueReport() - { - - } - - /** - * Gets the name of the report. - *

- * The name of the report must be unique amongst all installed implementations. The name of the report - * is examined by the Qpid immediately upon construction. The name should not change during - * the lifetime of the object (the value is only meaningful to the system at the time of initial construction) - * and all instances of the same concrete implementation should have the same name. - *

- * @return the name of the report - */ - public abstract String getName(); - - /** - * Get the name of the queue against which the report is being run. - * - * @return the name of the queue - */ - public final String getQueueName() - { - return _queue.getName(); - } - - final void setQueue(final Queue queue) - { - _queue = queue; - } - - /** - * Get the name of the virtual host against which the report is being run. - * - * @return the name of the virtual host - */ - public final String getVirtualHostName() - { - return _queue.getParent(VirtualHost.class).getName(); - } - - /** - * - * The value returned by getContentType() will be used to set the Content-Type HTTP header field - * - * @return the value to use for the content-type HTTP header field - */ - public abstract String getContentType(); - - /** - * Called by the system to add a message to the report. - * - *

- * The method is called by the system for every message on the queue, or until {@link #isComplete()} returns true. - *

- * @param reportableMessage the message to add to the report - */ - public abstract void addMessage(final ReportableMessage reportableMessage); - - /** - * Informs the system if the report is complete (i.e. does not need to report on any more messages). - * - *

- * This method will be called by the system after each message is {@link #addMessage(ReportableMessage) added} - * to the report. If a report is only interested in some messages, and can determine that the addition of more - * messages will not vary the content of the report, then it can return true. - *

- *

- * If this method always returns false, then all messages from the queue will be added to the report. - *

- *

- * NOTE: Retrieving content or properties of the message may require it to be reloaded from disk, and so care - * should be taken by reports to only access properties/content of the message if it is going to be required - * for the report production. - *

- * - * @return true if the report does not want to report on any more messages in the queue - */ - public abstract boolean isComplete(); - - /** - * Called by the system to get the content of the report to retrun to the user. - *

- * The system guarantees to only call this method once - *

- * @return the report content. - */ - public abstract T getReport(); - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/QueueTextReport.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/QueueTextReport.java deleted file mode 100644 index 09bc5c4229..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/QueueTextReport.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.management.plugin.report; - -public abstract class QueueTextReport extends QueueReport -{ - public QueueTextReport() - { - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportRunner.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportRunner.java deleted file mode 100644 index 2a05cfc9a1..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportRunner.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.server.management.plugin.report; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.ServiceLoader; -import java.util.Set; -import java.util.UUID; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.queue.QueueEntry; -import org.apache.qpid.server.queue.QueueEntryVisitor; - -public class ReportRunner -{ - private static final Logger LOGGER = LoggerFactory.getLogger(ReportRunner.class); - - private static final Set IMMUTABLE_CLASSES = new HashSet<>(Arrays.asList( - Boolean.class, - Byte.class, - Short.class, - Character.class, - Integer.class, - Long.class, - Float.class, - Double.class, - UUID.class, - Date.class, - String.class - )); - - private ReportRunner(final QueueReport report) - { - _report = report; - } - - public boolean isBinaryReport() - { - return _report instanceof QueueBinaryReport; - } - - public static ReportRunner createRunner(final String reportName, final Map parameterMap) - { - QueueReport report = getReport(reportName); - setReportParameters(report, parameterMap); - return new ReportRunner<>(report); - } - - private static void setReportParameters(final QueueReport report, final Map parameterMap) - { - if(parameterMap != null && !parameterMap.isEmpty()) - { - Class clazz = report.getClass(); - for(Map.Entry entry : parameterMap.entrySet()) - { - String key = entry.getKey(); - String[] value = entry.getValue(); - if(isValidName(key)) - { - - StringBuilder setterName = new StringBuilder("set"); - setterName.append(key.substring(0,1).toUpperCase()); - if(key.length()>1) - { - setterName.append(key.substring(1)); - } - Method method = null; - try - { - - if (value == null || value.length == 0 || value.length == 1) - { - try - { - method = clazz.getMethod(setterName.toString(), String.class); - method.invoke(report, value == null || value.length == 0 ? null : value[0]); - } - catch (NoSuchMethodException | IllegalAccessException e) - { - method = null; - } - } - if (method == null) - { - try - { - method = clazz.getMethod(setterName.toString(), String[].class); - method.invoke(report, new Object[] { value }); - } - catch (NoSuchMethodException | IllegalAccessException e) - { - LOGGER.info("Unknown parameter '" - + key - + "' (no setter) for report " - + report.getName()); - } - } - } - catch (InvocationTargetException e) - { - LOGGER.info("Error setting parameter '" + key + "' for report " + report.getName(), e); - } - } - else - { - LOGGER.info("Invalid parameter name '" + key + "' running report " + report.getName()); - } - } - } - } - - private static boolean isValidName(final String key) - { - if(key != null && key.length() != 0) - { - if(Character.isJavaIdentifierStart(key.charAt(0))) - { - for(int i = 1; i < key.length(); i++) - { - if(!Character.isJavaIdentifierPart(key.charAt(i))) - { - return false; - } - } - return true; - } - - } - return false; - - } - - private static QueueReport getReport(final String reportName) - { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - for (final QueueReport report : ServiceLoader.load(QueueReport.class, classLoader)) - { - if (report.getName().equals(reportName)) - { - try - { - return report.getClass().newInstance(); - } - catch (InstantiationException | IllegalAccessException e) - { - // can't happen as by definition must have public noargs constructor - } - } - } - throw new IllegalArgumentException("Unknown report: " + reportName); - } - - public String getContentType() - { - return _report.getContentType(); - } - - - private static class ReportVisitor implements QueueEntryVisitor - { - - private final QueueReport _report; - - public ReportVisitor(final QueueReport report) - { - _report = report; - } - - @Override - public boolean visit(final QueueEntry entry) - { - _report.addMessage(convertMessage(entry.getMessage())); - return _report.isComplete(); - } - - - } - - - private static ReportableMessage convertMessage(final ServerMessage message) - { - return new ReportableMessage() - { - @Override - public String getInitialRoutingAddress() - { - return message.getInitialRoutingAddress(); - } - - @Override - public ReportableMessageHeader getMessageHeader() - { - return convertMessageHeader(message.getMessageHeader()); - } - - @Override - public ByteBuffer getContent() - { - ByteBuffer content = message.getContent(0, (int) getSize()); - - return content.asReadOnlyBuffer(); - } - - @Override - public boolean isPersistent() - { - return message.isPersistent(); - } - - @Override - public long getSize() - { - return message.getSize(); - } - - @Override - public long getExpiration() - { - return message.getExpiration(); - } - - @Override - public long getMessageNumber() - { - return message.getMessageNumber(); - } - - @Override - public long getArrivalTime() - { - return message.getArrivalTime(); - } - }; - } - - private static ReportableMessageHeader convertMessageHeader(final AMQMessageHeader messageHeader) - { - return new ReportableMessageHeader() - { - @Override - public String getCorrelationId() - { - return messageHeader.getCorrelationId(); - } - - @Override - public long getExpiration() - { - return messageHeader.getExpiration(); - } - - @Override - public String getUserId() - { - return messageHeader.getUserId(); - } - - @Override - public String getAppId() - { - return messageHeader.getAppId(); - } - - @Override - public String getMessageId() - { - return messageHeader.getMessageId(); - } - - @Override - public String getMimeType() - { - return messageHeader.getMimeType(); - } - - @Override - public String getEncoding() - { - return messageHeader.getEncoding(); - } - - @Override - public byte getPriority() - { - return messageHeader.getPriority(); - } - - @Override - public long getTimestamp() - { - return messageHeader.getTimestamp(); - } - - @Override - public String getType() - { - return messageHeader.getType(); - } - - @Override - public String getReplyTo() - { - return messageHeader.getReplyTo(); - } - - @Override - public Object getHeader(final String name) - { - return makeImmutable(messageHeader.getHeader(name)); - } - - @Override - public boolean containsHeaders(final Set names) - { - return messageHeader.containsHeaders(names); - } - - @Override - public boolean containsHeader(final String name) - { - return messageHeader.containsHeader(name); - } - - @Override - public Collection getHeaderNames() - { - return Collections.unmodifiableCollection(messageHeader.getHeaderNames()); - } - }; - } - - private static Object makeImmutable(final Object value) - { - if(value == null || IMMUTABLE_CLASSES.contains(value.getClass())) - { - return value; - } - else if(value instanceof byte[]) - { - return ByteBuffer.wrap((byte[])value).asReadOnlyBuffer(); - } - else if(value instanceof List) - { - List orig = (List) value; - List copy = new ArrayList<>(orig.size()); - for(Object element : orig) - { - copy.add(makeImmutable(element)); - } - return copy; - } - else if(value instanceof Map) - { - Map orig = (Map) value; - LinkedHashMap copy = new LinkedHashMap<>(); - for(Map.Entry entry : orig.entrySet()) - { - copy.put(makeImmutable(entry.getKey()),makeImmutable(entry.getValue())); - } - return copy; - } - else return null; - } - - private final QueueReport _report; - - public final T runReport(Queue queue) - { - _report.setQueue(queue); - ReportVisitor visitor = new ReportVisitor(_report); - queue.visit(visitor); - return _report.getReport(); - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportableMessage.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportableMessage.java deleted file mode 100644 index 00b6c4abeb..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportableMessage.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.management.plugin.report; - -import java.nio.ByteBuffer; - -public interface ReportableMessage -{ - String getInitialRoutingAddress(); - - ReportableMessageHeader getMessageHeader(); - - public ByteBuffer getContent(); - - boolean isPersistent(); - - long getSize(); - - long getExpiration(); - - long getMessageNumber(); - - long getArrivalTime(); -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportableMessageHeader.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportableMessageHeader.java deleted file mode 100644 index e78415f8d0..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportableMessageHeader.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.management.plugin.report; - -import java.util.Collection; -import java.util.Set; - -public interface ReportableMessageHeader -{ - String getCorrelationId(); - - long getExpiration(); - - String getUserId(); - - String getAppId(); - - String getMessageId(); - - String getMimeType(); - - String getEncoding(); - - byte getPriority(); - - long getTimestamp(); - - String getType(); - - String getReplyTo(); - - Object getHeader(String name); - - boolean containsHeaders(Set names); - - boolean containsHeader(String name); - - Collection getHeaderNames(); - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/DefinedFileServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/DefinedFileServlet.java deleted file mode 100644 index 2f6f55e042..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/DefinedFileServlet.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.management.plugin.servlet; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.qpid.server.management.plugin.HttpManagementUtil; - -public class DefinedFileServlet extends HttpServlet -{ - - private static final String FILENAME_INIT_PARAMETER = "filename"; - - private String _filename; - - public DefinedFileServlet() - { - super(); - } - - public DefinedFileServlet(String filename) - { - _filename = filename; - } - - @Override - public void init() throws ServletException - { - ServletConfig config = getServletConfig(); - String fileName = config.getInitParameter(FILENAME_INIT_PARAMETER); - if (fileName != null && !"".equals(fileName)) - { - _filename = fileName; - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - try (OutputStream output = HttpManagementUtil.getOutputStream(request, response)) - { - try(InputStream fileInput = getClass().getResourceAsStream("/resources/" + _filename)) - { - if (fileInput != null) - { - byte[] buffer = new byte[1024]; - response.setStatus(HttpServletResponse.SC_OK); - int read = 0; - - while ((read = fileInput.read(buffer)) > 0) - { - output.write(buffer, 0, read); - } - } - else - { - response.sendError(HttpServletResponse.SC_NOT_FOUND, "unknown file: " + _filename); - } - } - } - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/FileServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/FileServlet.java deleted file mode 100644 index 1c741d97e8..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/FileServlet.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.management.plugin.servlet; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URL; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.qpid.server.management.plugin.HttpManagementUtil; - -public class FileServlet extends HttpServlet -{ - private static final String RESOURCES_PREFIX = "/resources"; - private static final Map CONTENT_TYPES; - - static - { - - Map contentTypes = new HashMap(); - contentTypes.put("js", "application/javascript"); - contentTypes.put("html", "text/html"); - contentTypes.put("css", "text/css"); - contentTypes.put("json", "application/json"); - contentTypes.put("jpg", "image/jpg"); - contentTypes.put("png", "image/png"); - contentTypes.put("gif", "image/gif"); - CONTENT_TYPES = Collections.unmodifiableMap(contentTypes); - } - - private final String _resourcePathPrefix; - private final boolean _usePathInfo; - - public FileServlet() - { - this(RESOURCES_PREFIX, false); - } - - public FileServlet(String resourcePathPrefix, boolean usePathInfo) - { - _resourcePathPrefix = resourcePathPrefix; - _usePathInfo = usePathInfo; - } - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - String filename = null; - if(_usePathInfo) - { - filename = request.getPathInfo(); - } - else - { - filename = request.getServletPath(); - } - - if(filename.contains(".")) - { - String suffix = filename.substring(filename.lastIndexOf('.')+1); - String contentType = CONTENT_TYPES.get(suffix); - if(contentType != null) - { - response.setContentType(contentType); - } - } - - URL resourceURL = getClass().getResource(_resourcePathPrefix + filename); - if(resourceURL != null) - { - response.setStatus(HttpServletResponse.SC_OK); - InputStream fileInput = resourceURL.openStream(); - try - { - byte[] buffer = new byte[1024]; - int read = 0; - OutputStream output = HttpManagementUtil.getOutputStream(request, response); - try - { - while((read = fileInput.read(buffer)) != -1) - { - output.write(buffer, 0, read); - } - } - finally - { - output.close(); - } - } - finally - { - fileInput.close(); - } - } - else - { - response.sendError(HttpServletResponse.SC_NOT_FOUND, "unknown file"); - } - - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/LogFileServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/LogFileServlet.java deleted file mode 100644 index 321cfae66c..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/LogFileServlet.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.management.plugin.servlet; - -import java.io.IOException; -import java.io.OutputStream; -import java.text.SimpleDateFormat; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.log4j.LogManager; -import org.apache.qpid.server.management.plugin.log.LogFileDetails; -import org.apache.qpid.server.management.plugin.log.LogFileHelper; -import org.apache.qpid.server.management.plugin.servlet.rest.AbstractServlet; - -public class LogFileServlet extends AbstractServlet -{ - private static final String PARAMETER_LOG_FILE = "l"; - - private static final long serialVersionUID = 1L; - - public static final String LOGS_FILE_NAME = "qpid-logs-%s.zip"; - public static final String DATE_FORMAT = "yyyy-MM-dd-mmHHss"; - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws IOException, - ServletException - { - response.setHeader("Cache-Control", "no-cache"); - response.setHeader("Pragma", "no-cache"); - response.setDateHeader("Expires", 0); - - if (!getBroker().getSecurityManager().authoriseLogsAccess()) - { - response.sendError(HttpServletResponse.SC_FORBIDDEN, "Log files download is denied"); - return; - } - - String[] requestedFiles = request.getParameterValues(PARAMETER_LOG_FILE); - - if (requestedFiles == null || requestedFiles.length == 0) - { - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - return; - } - - @SuppressWarnings("unchecked") - LogFileHelper helper = new LogFileHelper(Collections.list(LogManager.getRootLogger().getAllAppenders())); - - List logFiles = null; - - try - { - logFiles = helper.findLogFileDetails(requestedFiles); - } - catch(IllegalArgumentException e) - { - response.sendError(HttpServletResponse.SC_BAD_REQUEST); - return; - } - - if (logFiles.size() == 0) - { - response.sendError(HttpServletResponse.SC_NOT_FOUND); - return; - } - - String fileName = String.format(LOGS_FILE_NAME, new SimpleDateFormat(DATE_FORMAT).format(new Date())); - response.setStatus(HttpServletResponse.SC_OK); - response.setHeader("Content-Disposition", "attachment;filename=" + fileName); - response.setContentType(LogFileHelper.ZIP_MIME_TYPE); - - OutputStream os = response.getOutputStream(); - try - { - helper.writeLogFiles(logFiles, os); - } - finally - { - if (os != null) - { - os.close(); - } - } - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/ServletConnectionPrincipal.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/ServletConnectionPrincipal.java deleted file mode 100644 index 18a026ec93..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/ServletConnectionPrincipal.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.management.plugin.servlet; - -import org.apache.qpid.server.security.auth.ManagementConnectionPrincipal; -import org.apache.qpid.server.security.auth.SocketConnectionPrincipal; - -import javax.servlet.ServletRequest; -import java.net.InetSocketAddress; -import java.net.SocketAddress; - -public class ServletConnectionPrincipal implements ManagementConnectionPrincipal -{ - private final InetSocketAddress _address; - - public ServletConnectionPrincipal(ServletRequest request) - { - _address = new InetSocketAddress(request.getRemoteHost(), request.getRemotePort()); - } - - @Override - public SocketAddress getRemoteAddress() - { - return _address; - } - - @Override - public String getName() - { - return _address.toString(); - } - - @Override - public boolean equals(final Object o) - { - if (this == o) - { - return true; - } - if (o == null || getClass() != o.getClass()) - { - return false; - } - - final ServletConnectionPrincipal that = (ServletConnectionPrincipal) o; - - if (!_address.equals(that._address)) - { - return false; - } - - return true; - } - - @Override - public int hashCode() - { - return _address.hashCode(); - } - - @Override - public String getType() - { - return "HTTP"; - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/AbstractServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/AbstractServlet.java deleted file mode 100644 index ef32d352bb..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/AbstractServlet.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.plugin.servlet.rest; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.Writer; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; - -import javax.security.auth.Subject; -import javax.servlet.ServletConfig; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.codehaus.jackson.JsonGenerationException; -import org.codehaus.jackson.map.JsonMappingException; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.management.plugin.HttpManagementConfiguration; -import org.apache.qpid.server.management.plugin.HttpManagementUtil; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; - -public abstract class AbstractServlet extends HttpServlet -{ - private static final Logger LOGGER = LoggerFactory.getLogger(AbstractServlet.class); - - private Broker _broker; - private HttpManagementConfiguration _managementConfiguration; - - protected AbstractServlet() - { - super(); - } - - @Override - public void init() throws ServletException - { - ServletConfig servletConfig = getServletConfig(); - ServletContext servletContext = servletConfig.getServletContext(); - _broker = HttpManagementUtil.getBroker(servletContext); - _managementConfiguration = HttpManagementUtil.getManagementConfiguration(servletContext); - super.init(); - } - - @Override - protected final void doGet(final HttpServletRequest request, final HttpServletResponse resp) - { - doWithSubjectAndActor( - new PrivilegedExceptionAction() - { - @Override - public Void run() throws Exception - { - doGetWithSubjectAndActor(request, resp); - return null; - } - }, - request, - resp - ); - } - - /** - * Performs the GET action as the logged-in {@link Subject}. - * Subclasses commonly override this method - */ - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException - { - throw new UnsupportedOperationException("GET not supported by this servlet"); - } - - - @Override - protected final void doPost(final HttpServletRequest request, final HttpServletResponse resp) - { - doWithSubjectAndActor( - new PrivilegedExceptionAction() - { - @Override - public Void run() throws Exception - { - doPostWithSubjectAndActor(request, resp); - return null; - } - }, - request, - resp - ); - } - - /** - * Performs the POST action as the logged-in {@link Subject}. - * Subclasses commonly override this method - */ - protected void doPostWithSubjectAndActor(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException - { - throw new UnsupportedOperationException("POST not supported by this servlet"); - } - - @Override - protected final void doPut(final HttpServletRequest request, final HttpServletResponse resp) - { - doWithSubjectAndActor( - new PrivilegedExceptionAction() - { - @Override - public Void run() throws Exception - { - doPutWithSubjectAndActor(request, resp); - return null; - } - }, - request, - resp - ); - } - - public Writer getOutputWriter(final HttpServletRequest request, final HttpServletResponse response) - throws IOException - { - return HttpManagementUtil.getOutputWriter(request, response, _managementConfiguration); - } - - public OutputStream getOutputStream(final HttpServletRequest request, final HttpServletResponse response) - throws IOException - { - return HttpManagementUtil.getOutputStream(request, response, _managementConfiguration); - } - - /** - * Performs the PUT action as the logged-in {@link Subject}. - * Subclasses commonly override this method - */ - protected void doPutWithSubjectAndActor(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException - { - throw new UnsupportedOperationException("PUT not supported by this servlet"); - } - - @Override - protected final void doDelete(final HttpServletRequest request, final HttpServletResponse resp) - throws ServletException, IOException - { - doWithSubjectAndActor( - new PrivilegedExceptionAction() - { - @Override - public Void run() throws Exception - { - doDeleteWithSubjectAndActor(request, resp); - return null; - } - }, - request, - resp - ); - } - - /** - * Performs the PUT action as the logged-in {@link Subject}. - * Subclasses commonly override this method - */ - protected void doDeleteWithSubjectAndActor(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException - { - throw new UnsupportedOperationException("DELETE not supported by this servlet"); - } - - private void doWithSubjectAndActor( - PrivilegedExceptionAction privilegedExceptionAction, - final HttpServletRequest request, - final HttpServletResponse resp) - { - Subject subject; - try - { - subject = getAuthorisedSubject(request); - } - catch (SecurityException e) - { - sendError(resp, HttpServletResponse.SC_UNAUTHORIZED); - return; - } - - try - { - Subject.doAs(subject, privilegedExceptionAction); - } - catch(RuntimeException e) - { - LOGGER.error("Unable to perform action", e); - throw e; - } - catch (PrivilegedActionException e) - { - LOGGER.error("Unable to perform action", e); - Throwable cause = e.getCause(); - if(cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - if(cause instanceof Error) - { - throw (Error)cause; - } - throw new ConnectionScopedRuntimeException(e.getCause()); - } - } - - protected Subject getAuthorisedSubject(HttpServletRequest request) - { - Subject subject = HttpManagementUtil.getAuthorisedSubject(request.getSession()); - if (subject == null) - { - throw new SecurityException("Access to management rest interfaces is denied for un-authorised user"); - } - return subject; - } - - protected Broker getBroker() - { - return _broker; - } - - protected HttpManagementConfiguration getManagementConfiguration() - { - return _managementConfiguration; - } - - protected void sendError(final HttpServletResponse resp, int errorCode) - { - try - { - resp.sendError(errorCode); - } - catch (IOException e) - { - throw new ConnectionScopedRuntimeException("Failed to send error response code " + errorCode, e); - } - } - - protected void sendJsonResponse(Object object, HttpServletRequest request, HttpServletResponse response) throws IOException, - JsonGenerationException, JsonMappingException - { - response.setStatus(HttpServletResponse.SC_OK); - - response.setHeader("Cache-Control","no-cache"); - response.setHeader("Pragma","no-cache"); - response.setDateHeader ("Expires", 0); - response.setContentType("application/json"); - - final Writer writer = getOutputWriter(request, response); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, object); - } - - protected String[] getPathInfoElements(HttpServletRequest request) - { - String pathInfo = request.getPathInfo(); - if (pathInfo != null && pathInfo.length() > 0) - { - return pathInfo.substring(1).split("/"); - } - return null; - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/Action.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/Action.java deleted file mode 100644 index 3241a7560e..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/Action.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.server.management.plugin.servlet.rest; - -import java.util.Map; - -import org.apache.qpid.server.model.Broker; - - -public interface Action -{ - String getName(); - Object perform(Map request, Broker broker); -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/ApiDocsServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/ApiDocsServlet.java deleted file mode 100644 index 5c30378fc6..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/ApiDocsServlet.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.server.management.plugin.servlet.rest; - -import java.io.IOException; -import java.io.PrintWriter; -import java.io.Writer; -import java.security.AccessControlException; -import java.util.*; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.Part; - -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.AbstractConfiguredObject; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredAutomatedAttribute; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.ConfiguredObjectAttribute; -import org.apache.qpid.server.model.IllegalStateTransitionException; -import org.apache.qpid.server.model.IntegrityViolationException; -import org.apache.qpid.server.model.ManagedObject; -import org.apache.qpid.server.model.Model; -import org.apache.qpid.server.util.urlstreamhandler.data.Handler; -import org.apache.qpid.server.virtualhost.ExchangeExistsException; -import org.apache.qpid.server.virtualhost.QueueExistsException; -import org.apache.qpid.util.DataUrlUtils; - -public class ApiDocsServlet extends AbstractServlet -{ - private static final Logger LOGGER = LoggerFactory.getLogger(ApiDocsServlet.class); - private final Model _model; - private final List> _types; - - private Class[] _hierarchy; - - private static final Set VOWELS = new HashSet<>(Arrays.asList('a','e','i','o','u')); - - public static final Comparator> CLASS_COMPARATOR = - new Comparator>() - { - @Override - public int compare(final Class o1, - final Class o2) - { - return o1.getSimpleName().compareTo(o2.getSimpleName()); - } - - }; - private static final Map, List> REGISTERED_CLASSES = new TreeMap<>(CLASS_COMPARATOR); - - - public ApiDocsServlet(final Model model, final List registeredPaths, Class... hierarchy) - { - super(); - _model = model; - _hierarchy = hierarchy; - _types = hierarchy.length == 0 ? null : new ArrayList<>(_model.getTypeRegistry().getTypeSpecialisations(getConfiguredClass())); - if(_types != null) - { - Collections.sort(_types, CLASS_COMPARATOR); - } - if(_hierarchy.length != 0) - { - List paths = REGISTERED_CLASSES.get(getConfiguredClass()); - if(paths == null) - { - paths = new ArrayList<>(); - REGISTERED_CLASSES.put(getConfiguredClass(), paths); - } - paths.addAll(registeredPaths); - - } - - } - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - response.setContentType("text/html"); - response.setStatus(HttpServletResponse.SC_OK); - - - PrintWriter writer = response.getWriter(); - - writePreamble(writer); - writeHead(writer); - - if(_hierarchy.length == 0) - { - writer.println(""); - writer.println(""); - writer.println(""); - writer.println(""); - writer.println(""); - writer.println(""); - writer.println(""); - writer.println(""); - writer.println(""); - for(Map.Entry, List> entry : REGISTERED_CLASSES.entrySet()) - { - List paths = entry.getValue(); - Class objClass = entry.getKey(); - writer.println(""); - writer.println(""); - writer.println(""); - writer.println(""); - writer.println(""); - for(int i = 1; i < paths.size(); i++) - { - writer.println(""); - writer.println(""); - writer.println(""); - } - - } - writer.println(""); - writer.println("
TypePathDescription
"+objClass.getSimpleName()+"" + paths.get(0) + ""+ - objClass.getAnnotation(ManagedObject.class).description()+"
" + paths.get(i) + "
"); - - } - else - { - writeCategoryDescription(writer); - writeUsage(writer, request); - writeTypes(writer); - writeAttributes(writer); - } - - writeFoot(writer); - } - - private void writePreamble(final PrintWriter writer) - { - writer.println(""); - writer.println(""); - - - } - - private void writeHead(final PrintWriter writer) - { - writer.println(""); - writer.println(""); - writeTitle(writer); - - writer.println(""); - writer.println(""); - } - - private void writeTitle(final PrintWriter writer) - { - writer.print(""); - if(_hierarchy.length == 0) - { - writer.print("Qpid API"); - } - else - { - writer.print("Qpid API: " + getConfiguredClass().getSimpleName()); - } - writer.println(""); - } - - private void writeCategoryDescription(PrintWriter writer) - { - writer.println("

"+getConfiguredClass().getSimpleName()+"

"); - writer.println(getConfiguredClass().getAnnotation(ManagedObject.class).description()); - } - - private void writeUsage(final PrintWriter writer, final HttpServletRequest request) - { - writer.println("

Usage

"); - writer.println(""); - writer.println(""); - writer.print(""); - - writer.print(""); - writer.println("
ReadGET" + request.getServletPath() - .replace("apidocs", "api")); - - for (final Class category : _hierarchy) - { - writer.print("[/<" + category.getSimpleName().toLowerCase() + " name or id>"); - } - for(int i = 0; i < _hierarchy.length; i++) - { - writer.print("] "); - } - writer.println("
UpdatePUT or POST" - + request.getServletPath().replace("apidocs", "api")); - for (final Class category : _hierarchy) - { - writer.print("/<" + category.getSimpleName().toLowerCase() + " name or id>"); - } - - writer.print( - "
CreatePUT or POST" - + request.getServletPath().replace("apidocs", "api")); - for (int i = 0; i < _hierarchy.length - 1; i++) - { - writer.print("/<" + _hierarchy[i].getSimpleName().toLowerCase() + " name or id>"); - } - - writer.print("
DeleteDELETE" - + request.getServletPath().replace("apidocs", "api")); - for (final Class category : _hierarchy) - { - writer.print("/<" + category.getSimpleName().toLowerCase() + " name or id>"); - } - - writer.println("
"); - - } - - - private void writeTypes(final PrintWriter writer) - { - if(!_types.isEmpty() && !(_types.size() == 1 && getTypeName(_types.iterator().next()).trim().equals(""))) - { - writer.println("

Types

"); - writer.println(""); - writer.println(""); - writer.println(""); - writer.println(""); - - writer.println(""); - for (Class type : _types) - { - writer.print(""); - - } - writer.println(""); - } - - writer.println("
TypeDescription
"); - writer.print(getTypeName(type)); - writer.print(""); - writer.print(type.getAnnotation(ManagedObject.class).description()); - writer.println("
"); - } - - private String getTypeName(final Class type) - { - return type.getAnnotation(ManagedObject.class).type() == null - ? _model.getTypeRegistry().getTypeClass(type).getSimpleName() - : type.getAnnotation(ManagedObject.class).type(); - } - - private void writeAttributes(final PrintWriter writer) - { - writer.println("

Attributes

"); - writer.println("

Common Attributes

"); - - writeAttributesTable(writer, _model.getTypeRegistry().getAttributeTypes(getConfiguredClass()).values()); - - for(Class type : _types) - { - - ManagedObject typeAnnotation = type.getAnnotation(ManagedObject.class); - String typeName = typeAnnotation.type() == null ? _model.getTypeRegistry().getTypeClass(type).getSimpleName() : typeAnnotation.type(); - Collection> typeSpecificAttributes = - _model.getTypeRegistry().getTypeSpecificAttributes(type); - if(!typeSpecificAttributes.isEmpty()) - { - writer.println("

"+typeName+" Specific Attributes

"); - writeAttributesTable(writer, typeSpecificAttributes); - } - - - } - - } - - private void writeAttributesTable(final PrintWriter writer, - final Collection> attributeTypes) - { - writer.println(""); - writer.println(""); - writer.println(""); - writer.println(""); - writer.println(""); - - for(ConfiguredObjectAttribute attribute : attributeTypes) - { - if(!attribute.isDerived()) - { - writer.println(""); - } - } - writer.println(""); - - writer.println("
Attribute NameTypeDescription
" - + attribute.getName() - + "" - + renderType(attribute) - + "" - + attribute.getDescription() - + "
"); - - } - - private String renderType(final ConfiguredObjectAttribute attribute) - { - final Class type = attribute.getType(); - if(Enum.class.isAssignableFrom(type)) - { - return "
string
"; - } - else if(ConfiguredObject.class.isAssignableFrom(type)) - { - return "
string
"; - } - else if(UUID.class == type) - { - return "
string
"; - } - else - { - boolean hasValuesRestriction = attribute instanceof ConfiguredAutomatedAttribute - && ((ConfiguredAutomatedAttribute)attribute).hasValidValues(); - - StringBuilder returnVal = new StringBuilder(); - if(hasValuesRestriction) - { - returnVal.append("
"); - } - - if(Number.class.isAssignableFrom(type)) - { - returnVal.append("number"); - } - else if(Boolean.class == type) - { - returnVal.append("boolean"); - } - else if(String.class == type) - { - returnVal.append("string"); - } - else if(Collection.class.isAssignableFrom(type)) - { - // TODO - generate a description of the type in the array - returnVal.append("array"); - } - else if(Map.class.isAssignableFrom(type)) - { - // TODO - generate a description of the type in the object - returnVal.append("object"); - } - else - { - returnVal.append(type.getSimpleName()); - } - if(hasValuesRestriction) - { - returnVal.append("
"); - } - return returnVal.toString(); - } - } - - private void writeFoot(final PrintWriter writer) - { - writer.println(""); - writer.println(""); - } - private Class getConfiguredClass() - { - return _hierarchy.length == 0 ? Broker.class : _hierarchy[_hierarchy.length-1]; - } - - - private int getIntParameterFromRequest(final HttpServletRequest request, - final String paramName, - final int defaultValue) - { - int intValue = defaultValue; - final String stringValue = request.getParameter(paramName); - if(stringValue!=null) - { - try - { - intValue = Integer.parseInt(stringValue); - } - catch (NumberFormatException e) - { - LOGGER.warn("Could not parse " + stringValue + " as integer for parameter " + paramName); - } - } - return intValue; - } - - private boolean getBooleanParameterFromRequest(HttpServletRequest request, final String paramName) - { - return Boolean.parseBoolean(request.getParameter(paramName)); - } - - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/ConfiguredObjectToMapConverter.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/ConfiguredObjectToMapConverter.java deleted file mode 100644 index 0f1b7d03e9..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/ConfiguredObjectToMapConverter.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.server.management.plugin.servlet.rest; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.ConfiguredObjectAttribute; -import org.apache.qpid.server.model.Model; - -public class ConfiguredObjectToMapConverter -{ - /** Name of the key used for the statistics map */ - public static final String STATISTICS_MAP_KEY = "statistics"; - - private static Set CONFIG_EXCLUDED_ATTRIBUTES = - new HashSet<>(Arrays.asList(ConfiguredObject.ID, - ConfiguredObject.DURABLE, - ConfiguredObject.CREATED_BY, - ConfiguredObject.CREATED_TIME, - ConfiguredObject.LAST_UPDATED_BY, - ConfiguredObject.LAST_UPDATED_TIME)); - - public Map convertObjectToMap(final ConfiguredObject confObject, - Class clazz, - int depth, - final boolean useActualValues, - final boolean inheritedActuals, - final boolean includeSystemContext, - final boolean extractAsConfig, - final int oversizeThreshold, - final boolean isSecureTransport - ) - { - Map object = new LinkedHashMap<>(); - - incorporateAttributesIntoMap(confObject, object, useActualValues, inheritedActuals, includeSystemContext, - extractAsConfig, oversizeThreshold, isSecureTransport); - if(!extractAsConfig) - { - incorporateStatisticsIntoMap(confObject, object); - } - - if(depth > 0) - { - incorporateChildrenIntoMap(confObject, clazz, depth, object, useActualValues, inheritedActuals, - includeSystemContext, extractAsConfig, oversizeThreshold, isSecureTransport); - } - return object; - } - - - private void incorporateAttributesIntoMap( - final ConfiguredObject confObject, - Map object, - final boolean useActualValues, - final boolean inheritedActuals, - final boolean includeSystemContext, - final boolean extractAsConfig, - final int oversizeThreshold, - final boolean isSecureTransport) - { - // if extracting as config add a fake attribute for each secondary parent - if(extractAsConfig && confObject.getModel().getParentTypes(confObject.getCategoryClass()).size()>1) - { - Iterator> parentClasses = - confObject.getModel().getParentTypes(confObject.getCategoryClass()).iterator(); - - // ignore the first parent which is supplied by structure - parentClasses.next(); - - while(parentClasses.hasNext()) - { - Class parentClass = parentClasses.next(); - ConfiguredObject parent = confObject.getParent(parentClass); - if(parent != null) - { - String categoryName = parentClass.getSimpleName(); - object.put(categoryName.substring(0,1).toLowerCase()+categoryName.substring(1), parent.getName()); - } - } - } - - for(String name : confObject.getAttributeNames()) - { - if (!(extractAsConfig && CONFIG_EXCLUDED_ATTRIBUTES.contains(name))) - { - Object value = - useActualValues ? confObject.getActualAttributes().get(name) : confObject.getAttribute(name); - if (value instanceof ConfiguredObject) - { - object.put(name, ((ConfiguredObject) value).getName()); - } - else if (ConfiguredObject.CONTEXT.equals(name)) - { - Map contextValues = new HashMap<>(); - if (useActualValues) - { - collectContext(contextValues, confObject.getModel(), confObject, inheritedActuals); - } - else - { - for (String contextName : confObject.getContextKeys(!includeSystemContext)) - { - contextValues.put(contextName, confObject.getContextValue(String.class, contextName)); - } - } - if (!contextValues.isEmpty()) - { - object.put(ConfiguredObject.CONTEXT, contextValues); - } - } - else if (value instanceof Collection) - { - List converted = new ArrayList<>(); - for (Object member : (Collection) value) - { - if (member instanceof ConfiguredObject) - { - converted.add(((ConfiguredObject) member).getName()); - } - else - { - converted.add(member); - } - } - object.put(name, converted); - } - else if (value != null) - { - ConfiguredObjectAttribute attribute = confObject.getModel() - .getTypeRegistry() - .getAttributeTypes(confObject.getClass()) - .get(name); - - if (attribute.isSecureValue(value) && !(isSecureTransport && extractAsConfig)) - { - // do not expose actual secure attribute value - // getAttribute() returns encoded value - value = confObject.getAttribute(name); - } - - if(attribute.isOversized() && !extractAsConfig && !useActualValues) - { - String valueString = String.valueOf(value); - if(valueString.length() > oversizeThreshold) - { - - String replacementValue = "".equals(attribute.getOversizedAltText()) - ? String.valueOf(value).substring(0, oversizeThreshold - 4) + "..." - : attribute.getOversizedAltText(); - - object.put(name, replacementValue); - } - else - { - object.put(name, value); - } - } - else - { - object.put(name, value); - } - } - else if (extractAsConfig) - { - ConfiguredObjectAttribute attribute = confObject.getModel() - .getTypeRegistry() - .getAttributeTypes(confObject.getClass()) - .get(name); - - if(attribute.isPersisted() && attribute.isDerived()) - { - object.put(name, confObject.getAttribute(name)); - } - } - } - } - } - - private void collectContext(Map contextValues, Model model, ConfiguredObject confObject, boolean inheritedContext) - { - Object value = confObject.getActualAttributes().get(ConfiguredObject.CONTEXT); - if (inheritedContext) - { - Collection> parents = model.getParentTypes(confObject.getCategoryClass()); - if(parents != null && !parents.isEmpty()) - { - ConfiguredObject parent = confObject.getParent(parents.iterator().next()); - if(parent != null) - { - collectContext(contextValues, model, parent, inheritedContext); - } - } - } - if (value instanceof Map) - { - contextValues.putAll((Map)value); - } - } - - private void incorporateStatisticsIntoMap( - final ConfiguredObject confObject, Map object) - { - - Map statMap = new TreeMap(confObject.getStatistics()); - - if(!statMap.isEmpty()) - { - object.put(STATISTICS_MAP_KEY, statMap); - } - - } - - private void incorporateChildrenIntoMap( - final ConfiguredObject confObject, - Class clazz, - int depth, - Map object, - final boolean useActualValues, - final boolean inheritedActuals, - final boolean includeSystemContext, - final boolean extractAsConfig, - final int oversizeThreshold, - final boolean isSecure) - { - List> childTypes = new ArrayList<>(confObject.getModel().getChildTypes(clazz)); - - Collections.sort(childTypes, new Comparator>() - { - @Override - public int compare(final Class o1, final Class o2) - { - return o1.getSimpleName().compareTo(o2.getSimpleName()); - } - }); - for(Class childClass : childTypes) - { - if(!(extractAsConfig && confObject.getModel().getParentTypes(childClass).iterator().next() != confObject.getCategoryClass())) - { - - Collection children = confObject.getChildren(childClass); - if(children != null) - { - List sortedChildren = new ArrayList(children); - Collections.sort(sortedChildren, new Comparator() - { - @Override - public int compare(final ConfiguredObject o1, final ConfiguredObject o2) - { - return o1.getName().compareTo(o2.getName()); - } - }); - - List> childObjects = new ArrayList<>(); - - for (ConfiguredObject child : sortedChildren) - { - if (!(extractAsConfig && !child.isDurable())) - { - childObjects.add(convertObjectToMap(child, - childClass, - depth - 1, - useActualValues, - inheritedActuals, - includeSystemContext, - extractAsConfig, - oversizeThreshold, - isSecure)); - } - } - - if (!childObjects.isEmpty()) - { - String childTypeSingular = childClass.getSimpleName().toLowerCase(); - object.put(childTypeSingular + (childTypeSingular.endsWith("s") ? "es" : "s"), childObjects); - } - } - } - } - } - - - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/HelperServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/HelperServlet.java deleted file mode 100644 index cafde3b7f9..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/HelperServlet.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.management.plugin.servlet.rest; - -import java.io.IOException; -import java.io.Writer; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; - -import org.apache.qpid.server.management.plugin.servlet.rest.action.ListAccessControlProviderAttributes; -import org.apache.qpid.server.management.plugin.servlet.rest.action.ListBrokerAttribute; -import org.apache.qpid.server.management.plugin.servlet.rest.action.ListGroupProviderAttributes; -import org.apache.qpid.server.management.plugin.servlet.rest.action.ListTimeZones; -import org.apache.qpid.server.model.Broker; - -public class HelperServlet extends AbstractServlet -{ - private static final long serialVersionUID = 1L; - - private static final String PARAM_ACTION = "action"; - - private Map _actions; - private ObjectMapper _mapper; - - public HelperServlet() - { - _mapper = new ObjectMapper(); - _mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - - Action[] supportedActions = { - new ListBrokerAttribute(Broker.PRODUCT_VERSION, "version"), - new ListGroupProviderAttributes(), - new ListAccessControlProviderAttributes(), - new PluginClassProviderAction(), - new ListTimeZones() - }; - - _actions = new HashMap(); - - for(Action action : supportedActions) - { - _actions.put(action.getName(), action); - } - } - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws ServletException, - IOException - { - perform(request, response); - } - - @Override - protected void doPostWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws ServletException, - IOException - { - perform(request, response); - } - - private void perform(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - String actionName = request.getParameter(PARAM_ACTION); - Action action = _actions.get(actionName); - if (action == null) - { - response.setStatus(HttpServletResponse.SC_NOT_FOUND); - return; - } - - Map parameters = new HashMap(); - @SuppressWarnings("unchecked") - Enumeration names = request.getParameterNames(); - while (names.hasMoreElements()) - { - String name = (String) names.nextElement(); - String[] values = request.getParameterValues(name); - if (values.length == 1) - { - parameters.put(name, values[0]); - } - else - { - parameters.put(name, values); - } - } - - Object output = action.perform(parameters, getBroker()); - if (output == null) - { - response.setStatus(HttpServletResponse.SC_NOT_FOUND); - return; - } - response.setContentType("application/json"); - final Writer writer = getOutputWriter(request, response); - _mapper.writeValue(writer, output); - - response.setStatus(HttpServletResponse.SC_OK); - - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/KeyComparator.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/KeyComparator.java deleted file mode 100644 index 3d862ce321..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/KeyComparator.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.management.plugin.servlet.rest; - -import java.util.Comparator; -import java.util.Map; - -class KeyComparator implements Comparator -{ - private String _key; - - public KeyComparator(final String key) - { - _key = key; - } - - public int compare(final Map o1, final Map o2) - { - Comparable left = (Comparable) o1.get(_key); - Comparable right = (Comparable) o2.get(_key); - - int result; - if(left == null) - { - result = right == null ? 0 : -1; - } - else - { - result = left.compareTo(right); - } - - return result; - - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LogFileListingServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LogFileListingServlet.java deleted file mode 100644 index a7889e4890..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LogFileListingServlet.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.plugin.servlet.rest; - -import java.io.IOException; -import java.io.Writer; -import java.util.Collections; -import java.util.List; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.log4j.LogManager; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; - -import org.apache.qpid.server.management.plugin.log.LogFileDetails; -import org.apache.qpid.server.management.plugin.log.LogFileHelper; - -public class LogFileListingServlet extends AbstractServlet -{ - private static final long serialVersionUID = 1L; - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws IOException, - ServletException - { - response.setHeader("Cache-Control", "no-cache"); - response.setHeader("Pragma", "no-cache"); - response.setDateHeader("Expires", 0); - - if (!getBroker().getSecurityManager().authoriseLogsAccess()) - { - response.sendError(HttpServletResponse.SC_FORBIDDEN, "Log files access is denied"); - return; - } - - @SuppressWarnings("unchecked") - LogFileHelper helper = new LogFileHelper(Collections.list(LogManager.getRootLogger().getAllAppenders())); - List logFiles = helper.getLogFileDetails(false); - response.setContentType("application/json"); - response.setStatus(HttpServletResponse.SC_OK); - - final Writer writer = getOutputWriter(request, response); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, logFiles); - - response.setStatus(HttpServletResponse.SC_OK); - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LogRecordsServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LogRecordsServlet.java deleted file mode 100644 index b9d58c8868..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LogRecordsServlet.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.management.plugin.servlet.rest; - -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; - -import org.apache.qpid.server.logging.LogRecorder; - -public class LogRecordsServlet extends AbstractServlet -{ - private static final long serialVersionUID = 2L; - - public static final String PARAM_LAST_LOG_ID = "lastLogId"; - - public LogRecordsServlet() - { - super(); - } - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException - { - response.setContentType("application/json"); - response.setStatus(HttpServletResponse.SC_OK); - - response.setHeader("Cache-Control","no-cache"); - response.setHeader("Pragma","no-cache"); - response.setDateHeader ("Expires", 0); - - if (!getBroker().getSecurityManager().authoriseLogsAccess()) - { - response.sendError(HttpServletResponse.SC_FORBIDDEN, "Broker logs access is denied"); - return; - } - - long lastLogId = 0; - try - { - lastLogId = Long.parseLong(request.getParameter(PARAM_LAST_LOG_ID)); - } - catch(Exception e) - { - // ignore null and incorrect parameter values - } - - List> logRecords = new ArrayList>(); - - LogRecorder logRecorder = getBroker().getLogRecorder(); - for(LogRecorder.Record record : logRecorder) - { - if (record.getId() > lastLogId) - { - logRecords.add(logRecordToObject(record)); - } - } - - final Writer writer = getOutputWriter(request,response); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, logRecords); - - response.setStatus(HttpServletResponse.SC_OK); - - } - - private Map logRecordToObject(LogRecorder.Record record) - { - Map recordMap = new LinkedHashMap(); - recordMap.put("id",record.getId()); - recordMap.put("timestamp", record.getTimestamp()); - recordMap.put("level", record.getLevel()); - recordMap.put("thread", record.getThreadName()); - recordMap.put("logger", record.getLogger()); - recordMap.put("message", record.getMessage()); - return recordMap; - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LoggedOnUserPreferencesServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LoggedOnUserPreferencesServlet.java deleted file mode 100644 index 6984a32e09..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LoggedOnUserPreferencesServlet.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.server.management.plugin.servlet.rest; - -import java.io.IOException; -import java.net.SocketAddress; -import java.security.Principal; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; - -import javax.security.auth.Subject; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.codehaus.jackson.map.ObjectMapper; - -import org.apache.qpid.server.management.plugin.HttpManagementUtil; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.PreferencesProvider; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; - -public class LoggedOnUserPreferencesServlet extends AbstractServlet -{ - private static final long serialVersionUID = 1L; - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws IOException, - ServletException - { - PreferencesProvider preferencesProvider = getPreferencesProvider(request); - if (preferencesProvider == null) - { - response.sendError(HttpServletResponse.SC_NOT_FOUND, "Preferences provider is not configured"); - return; - } - String userName = getAuthenticatedUserName(request); - Map preferences = preferencesProvider.getPreferences(userName); - if (preferences == null) - { - preferences = Collections.emptyMap(); - } - sendJsonResponse(preferences, request, response); - } - - /* - * replace preferences - */ - @Override - protected void doPutWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException - { - PreferencesProvider preferencesProvider = getPreferencesProvider(request); - if (preferencesProvider == null) - { - response.sendError(HttpServletResponse.SC_NOT_FOUND, "Preferences provider is not configured"); - return; - } - String userName = getAuthenticatedUserName(request); - - ObjectMapper mapper = new ObjectMapper(); - - @SuppressWarnings("unchecked") - Map newPreferences = mapper.readValue(request.getInputStream(), LinkedHashMap.class); - - preferencesProvider.deletePreferences(userName); - Map preferences = preferencesProvider.setPreferences(userName, newPreferences); - if (preferences == null) - { - preferences = Collections.emptyMap(); - } - sendJsonResponse(preferences, request, response); - } - - /* - * update preferences - */ - @Override - protected void doPostWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException - { - PreferencesProvider preferencesProvider = getPreferencesProvider(request); - if (preferencesProvider == null) - { - response.sendError(HttpServletResponse.SC_NOT_FOUND, "Preferences provider is not configured"); - return; - } - String userName = getAuthenticatedUserName(request); - - ObjectMapper mapper = new ObjectMapper(); - - @SuppressWarnings("unchecked") - Map newPreferences = mapper.readValue(request.getInputStream(), LinkedHashMap.class); - Map preferences = preferencesProvider.setPreferences(userName, newPreferences); - if (preferences == null) - { - preferences = Collections.emptyMap(); - } - sendJsonResponse(preferences, request, response); - } - - private String getAuthenticatedUserName(HttpServletRequest request) - { - Subject subject = getAuthorisedSubject(request); - Principal principal = AuthenticatedPrincipal.getAuthenticatedPrincipalFromSubject(subject); - return principal.getName(); - } - - private PreferencesProvider getPreferencesProvider(HttpServletRequest request) - { - AuthenticationProvider authenticationProvider = getManagementConfiguration().getAuthenticationProvider(request); - if (authenticationProvider == null) - { - throw new IllegalStateException("Authentication provider is not found"); - } - return authenticationProvider.getPreferencesProvider(); - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LogoutServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LogoutServlet.java deleted file mode 100644 index 34b115ed13..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/LogoutServlet.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.server.management.plugin.servlet.rest; - -import java.io.IOException; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.apache.qpid.server.management.plugin.HttpManagementUtil; - -@SuppressWarnings("serial") -public class LogoutServlet extends HttpServlet -{ - public static final String RETURN_URL_INIT_PARAM = "qpid.webui_logout_redirect"; - private String _returnUrl = HttpManagementUtil.ENTRY_POINT_PATH; - - @Override - public void init(ServletConfig config) throws ServletException - { - super.init(config); - - String initValue = config.getServletContext().getInitParameter(RETURN_URL_INIT_PARAM); - if(initValue != null) - { - _returnUrl = initValue; - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException - { - HttpSession session = request.getSession(false); - if(session != null) - { - // Invalidating the session will cause LoginLogoutReporter to log the user logoff. - session.invalidate(); - } - - resp.sendRedirect(_returnUrl); - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MapComparator.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MapComparator.java deleted file mode 100644 index 84d987813b..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MapComparator.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.management.plugin.servlet.rest; - -import java.util.Collections; -import java.util.Comparator; -import java.util.Map; - -class MapComparator implements Comparator -{ - private Comparator[] _sortKeys; - - public MapComparator(final String[] sortKeys) - { - _sortKeys = parseKeys(sortKeys); - } - - private static Comparator[] parseKeys(final String[] sortKeys) - { - Comparator[] comparators = new Comparator[sortKeys.length]; - for(int i = 0; i < sortKeys.length; i++) - { - String key = sortKeys[i]; - - if(key.startsWith("+") || key.startsWith(" ")) - { - comparators[i] = new KeyComparator(key.substring(1)); - } - else if(key.startsWith("-")) - { - comparators[i] = Collections.reverseOrder(new KeyComparator(key.substring(1))); - } - else - { - comparators[i] = new KeyComparator(key); - } - } - return comparators; - } - - - public int compare(final Map o1, final Map o2) - { - int result = 0; - for(int i = 0; i < _sortKeys.length; i++) - { - result = _sortKeys[i].compare(o1, o2); - if(result != 0) - { - return result; - } - } - return 0; - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MessageContentServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MessageContentServlet.java deleted file mode 100644 index db58e49eeb..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MessageContentServlet.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.management.plugin.servlet.rest; - -import java.io.IOException; -import java.nio.ByteBuffer; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.qpid.server.message.MessageDeletedException; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.queue.QueueEntry; -import org.apache.qpid.server.queue.QueueEntryVisitor; - -public class MessageContentServlet extends AbstractServlet -{ - public MessageContentServlet() - { - super(); - } - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException - { - String[] pathInfoElements = getPathInfoElements(request); - if(pathInfoElements != null && pathInfoElements.length > 2) - { - getMessageContent(request, response); - } - - } - - private void getMessageContent(HttpServletRequest request, HttpServletResponse response) throws IOException - { - Queue queue = getQueueFromRequest(request); - String path[] = getPathInfoElements(request); - MessageFinder finder = new MessageFinder(Long.parseLong(path[2])); - queue.visit(finder); - if(finder.isFound()) - { - response.setContentType(finder.getMimeType()); - response.setContentLength((int) finder.getSize()); - getOutputStream(request, response).write(finder.getContent()); - - } - - } - - private Queue getQueueFromRequest(HttpServletRequest request) - { - // TODO - validation that there is a vhost and queue and only those in the path - - String[] pathInfoElements = getPathInfoElements(request); - if(pathInfoElements == null || pathInfoElements.length < 2) - { - throw new IllegalArgumentException("Invalid path is specified"); - } - String vhostName = pathInfoElements[0]; - String queueName = pathInfoElements[1]; - - VirtualHost vhost = getBroker().findVirtualHostByName(vhostName); - if (vhost == null) - { - throw new IllegalArgumentException("Could not find virtual host with name '" + vhostName + "'"); - } - return getQueueFromVirtualHost(queueName, vhost); - } - - private Queue getQueueFromVirtualHost(String queueName, VirtualHost vhost) - { - Queue queue = null; - - for(Queue q : vhost.getQueues()) - { - if(q.getName().equals(queueName)) - { - queue = q; - break; - } - } - return queue; - } - - private class MessageFinder implements QueueEntryVisitor - { - private final long _messageNumber; - private String _mimeType; - private long _size; - private byte[] _content; - private boolean _found; - - private MessageFinder(long messageNumber) - { - _messageNumber = messageNumber; - } - - - public boolean visit(QueueEntry entry) - { - ServerMessage message = entry.getMessage(); - if(message != null) - { - if(_messageNumber == message.getMessageNumber()) - { - try - { - MessageReference reference = message.newReference(); - try - { - _mimeType = message.getMessageHeader().getMimeType(); - _size = message.getSize(); - _content = new byte[(int) _size]; - _found = true; - message.getContent(ByteBuffer.wrap(_content), 0); - } - finally - { - reference.release(); - } - return true; - } - catch (MessageDeletedException e) - { - // ignore - the message was deleted as we tried too look at it, treat as if no message found - } - } - - } - return false; - } - - public String getMimeType() - { - return _mimeType; - } - - public long getSize() - { - return _size; - } - - public byte[] getContent() - { - return _content; - } - - public boolean isFound() - { - return _found; - } - } - - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MessageServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MessageServlet.java deleted file mode 100644 index 38f7ef06bc..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MessageServlet.java +++ /dev/null @@ -1,568 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.plugin.servlet.rest; - -import java.io.IOException; -import java.io.Writer; -import java.security.AccessControlException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.consumer.ConsumerImpl; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.message.MessageDeletedException; -import org.apache.qpid.server.message.MessageReference; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.queue.QueueEntry; -import org.apache.qpid.server.queue.QueueEntryVisitor; -import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.store.TransactionLogResource; - -public class MessageServlet extends AbstractServlet -{ - private static final Logger LOGGER = LoggerFactory.getLogger(MessageServlet.class); - - public MessageServlet() - { - super(); - } - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException - { - String[] pathInfoElements = getPathInfoElements(request); - if(pathInfoElements != null && pathInfoElements.length > 2) - { - getMessageContent(request, response); - } - else - { - getMessageList(request, response); - } - - } - - private void getMessageContent(HttpServletRequest request, HttpServletResponse response) throws IOException - { - Queue queue = getQueueFromRequest(request); - String path[] = getPathInfoElements(request); - MessageFinder messageFinder = new MessageFinder(Long.parseLong(path[2])); - queue.visit(messageFinder); - - response.setStatus(HttpServletResponse.SC_OK); - - response.setHeader("Cache-Control","no-cache"); - response.setHeader("Pragma","no-cache"); - response.setDateHeader ("Expires", 0); - response.setContentType("application/json"); - - final Writer writer = getOutputWriter(request,response); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, messageFinder.getMessageObject()); - } - - private void getMessageList(HttpServletRequest request, HttpServletResponse response) throws IOException - { - Queue queue = getQueueFromRequest(request); - - int first = -1; - int last = -1; - String range = request.getHeader("Range"); - if(range != null) - { - String[] boundaries = range.split("=")[1].split("-"); - first = Integer.parseInt(boundaries[0]); - last = Integer.parseInt(boundaries[1]); - } - final MessageCollector messageCollector = new MessageCollector(first, last); - queue.visit(messageCollector); - - response.setContentType("application/json"); - final List> messages = messageCollector.getMessages(); - int queueSize = (int) queue.getQueueDepthMessages(); - String min = messages.isEmpty() ? "0" : messages.get(0).get("position").toString(); - String max = messages.isEmpty() ? "0" : messages.get(messages.size()-1).get("position").toString(); - response.setHeader("Content-Range", (min + "-" + max + "/" + queueSize)); - response.setStatus(HttpServletResponse.SC_OK); - - response.setHeader("Cache-Control","no-cache"); - response.setHeader("Pragma","no-cache"); - response.setDateHeader ("Expires", 0); - - final Writer writer = getOutputWriter(request,response); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, messages); - } - - private Queue getQueueFromRequest(HttpServletRequest request) - { - // TODO - validation that there is a vhost and queue and only those in the path - - String[] pathInfoElements = getPathInfoElements(request); - if(pathInfoElements == null || pathInfoElements.length < 2) - { - throw new IllegalArgumentException("Invalid path is specified"); - } - String vhostName = pathInfoElements[0]; - String queueName = pathInfoElements[1]; - - VirtualHost vhost = getBroker().findVirtualHostByName(vhostName); - if (vhost == null) - { - throw new IllegalArgumentException("Could not find virtual host with name '" + vhostName + "'"); - } - - Queue queueFromVirtualHost = getQueueFromVirtualHost(queueName, vhost); - if (queueFromVirtualHost == null) - { - throw new IllegalArgumentException("Could not find queue with name '" + queueName + "' on virtual host '" + vhost.getName() + "'"); - } - return queueFromVirtualHost; - } - - private Queue getQueueFromVirtualHost(String queueName, VirtualHost vhost) - { - Queue queue = null; - - for(Queue q : vhost.getQueues()) - { - - if(q.getName().equals(queueName)) - { - queue = q; - break; - } - } - return queue; - } - - private abstract static class QueueEntryTransaction implements VirtualHost.TransactionalOperation - { - private final Queue _sourceQueue; - private final List _messageIds; - - protected QueueEntryTransaction(Queue sourceQueue, List messageIds) - { - _sourceQueue = sourceQueue; - _messageIds = messageIds; - } - - @Override - public void withinTransaction(final VirtualHost.Transaction txn) - { - - _sourceQueue.visit(new QueueEntryVisitor() - { - - public boolean visit(final QueueEntry entry) - { - final ServerMessage message = entry.getMessage(); - if(message != null) - { - final long messageId = message.getMessageNumber(); - if (_messageIds.remove(messageId) || (messageId <= (long) Integer.MAX_VALUE - && _messageIds.remove(Integer.valueOf((int)messageId)))) - { - updateEntry(entry, txn); - } - } - return _messageIds.isEmpty(); - } - }); - } - - - protected abstract void updateEntry(QueueEntry entry, VirtualHost.Transaction txn); - } - - private static class MoveTransaction extends QueueEntryTransaction - { - private final Queue _destinationQueue; - - public MoveTransaction(Queue sourceQueue, List messageIds, Queue destinationQueue) - { - super(sourceQueue, messageIds); - _destinationQueue = destinationQueue; - } - - @Override - protected void updateEntry(QueueEntry entry, VirtualHost.Transaction txn) - { - ServerMessage msg = entry.getMessage(); - if(msg != null && !msg.isReferenced((TransactionLogResource)_destinationQueue)) - { - txn.move(entry, _destinationQueue); - } - } - } - - private static class CopyTransaction extends QueueEntryTransaction - { - private final Queue _destinationQueue; - - public CopyTransaction(Queue sourceQueue, List messageIds, Queue destinationQueue) - { - super(sourceQueue, messageIds); - _destinationQueue = destinationQueue; - } - - @Override - protected void updateEntry(QueueEntry entry, VirtualHost.Transaction txn) - { - ServerMessage msg = entry.getMessage(); - if(msg != null && !msg.isReferenced((TransactionLogResource)_destinationQueue)) - { - txn.copy(entry, _destinationQueue); - } - } - } - - private static class DeleteTransaction extends QueueEntryTransaction - { - public DeleteTransaction(Queue sourceQueue, List messageIds) - { - super(sourceQueue, messageIds); - } - - @Override - protected void updateEntry(QueueEntry entry, VirtualHost.Transaction txn) - { - txn.dequeue(entry); - } - } - - - private static class ClearQueueTransaction implements VirtualHost.TransactionalOperation - { - private final Queue _queue; - - protected ClearQueueTransaction(Queue queue) - { - _queue = queue; - } - - @Override - public void withinTransaction(final VirtualHost.Transaction txn) - { - _queue.visit(new QueueEntryVisitor() - { - - public boolean visit(final QueueEntry entry) - { - final ServerMessage message = entry.getMessage(); - if(message != null) - { - txn.dequeue(entry); - } - return false; - } - }); - - } - } - - private class MessageCollector implements QueueEntryVisitor - { - private final int _first; - private final int _last; - private int _position = -1; - private final List> _messages = new ArrayList>(); - - private MessageCollector(int first, int last) - { - _first = first; - _last = last; - } - - - public boolean visit(QueueEntry entry) - { - - _position++; - if((_first == -1 || _position >= _first) && (_last == -1 || _position <= _last)) - { - final Map messageObject = convertToObject(entry, false); - messageObject.put("position", _position); - _messages.add(messageObject); - } - return _last != -1 && _position > _last; - } - - public List> getMessages() - { - return _messages; - } - } - - - private class MessageFinder implements QueueEntryVisitor - { - private final long _messageNumber; - private Map _messageObject; - - private MessageFinder(long messageNumber) - { - _messageNumber = messageNumber; - } - - - public boolean visit(QueueEntry entry) - { - ServerMessage message = entry.getMessage(); - if(message != null) - { - if(_messageNumber == message.getMessageNumber()) - { - try - { - MessageReference reference = message.newReference(); - try - { - _messageObject = convertToObject(entry, true); - } - finally - { - reference.release(); - } - return true; - } - catch (MessageDeletedException e) - { - // ignore - the message has been deleted before we got a chance to look at it - } - } - } - return false; - } - - public Map getMessageObject() - { - return _messageObject; - } - } - - private Map convertToObject(QueueEntry entry, boolean includeContent) - { - Map object = new LinkedHashMap(); - object.put("size", entry.getSize()); - object.put("deliveryCount", entry.getDeliveryCount()); - object.put("state",entry.isAvailable() - ? "Available" - : entry.isAcquired() - ? "Acquired" - : ""); - final ConsumerImpl deliveredConsumer = entry.getDeliveredConsumer(); - object.put("deliveredTo", deliveredConsumer == null ? null : deliveredConsumer.getConsumerNumber()); - ServerMessage message = entry.getMessage(); - - if(message != null) - { - convertMessageProperties(object, message); - if(includeContent) - { - convertMessageHeaders(object, message); - } - } - - return object; - } - - private void convertMessageProperties(Map object, ServerMessage message) - { - object.put("id", message.getMessageNumber()); - object.put("arrivalTime",message.getArrivalTime()); - object.put("persistent", message.isPersistent()); - - final AMQMessageHeader messageHeader = message.getMessageHeader(); - if(messageHeader != null) - { - addIfPresent(object, "messageId", messageHeader.getMessageId()); - addIfPresentAndNotZero(object, "expirationTime", messageHeader.getExpiration()); - addIfPresent(object, "applicationId", messageHeader.getAppId()); - addIfPresent(object, "correlationId", messageHeader.getCorrelationId()); - addIfPresent(object, "encoding", messageHeader.getEncoding()); - addIfPresent(object, "mimeType", messageHeader.getMimeType()); - addIfPresent(object, "priority", messageHeader.getPriority()); - addIfPresent(object, "replyTo", messageHeader.getReplyTo()); - addIfPresentAndNotZero(object, "timestamp", messageHeader.getTimestamp()); - addIfPresent(object, "type", messageHeader.getType()); - addIfPresent(object, "userId", messageHeader.getUserId()); - } - - } - - private void addIfPresentAndNotZero(Map object, String name, Object property) - { - if(property instanceof Number) - { - Number value = (Number)property; - if (value.longValue() != 0) - { - object.put(name, property); - } - } - } - - private void addIfPresent(Map object, String name, Object property) - { - if(property != null) - { - object.put(name, property); - } - } - - private void convertMessageHeaders(Map object, ServerMessage message) - { - final AMQMessageHeader messageHeader = message.getMessageHeader(); - if(messageHeader != null) - { - Map headers = new HashMap(); - for(String headerName : messageHeader.getHeaderNames()) - { - headers.put(headerName, messageHeader.getHeader(headerName)); - } - object.put("headers", headers); - } - } - - /* - * POST moves or copies messages to the given queue from a queue specified in the posted JSON data - */ - @Override - protected void doPostWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - - try - { - final Queue sourceQueue = getQueueFromRequest(request); - - ObjectMapper mapper = new ObjectMapper(); - - @SuppressWarnings("unchecked") - Map providedObject = mapper.readValue(request.getInputStream(), LinkedHashMap.class); - - String destQueueName = (String) providedObject.get("destinationQueue"); - Boolean move = (Boolean) providedObject.get("move"); - - final VirtualHost vhost = sourceQueue.getParent(VirtualHost.class); - - boolean isMoveTransaction = move != null && Boolean.valueOf(move); - - // FIXME: added temporary authorization check until we introduce management layer - // and review current ACL rules to have common rules for all management interfaces - String methodName = isMoveTransaction? "moveMessages":"copyMessages"; - authorizeMethod(methodName, vhost); - - - final Queue destinationQueue = getQueueFromVirtualHost(destQueueName, vhost); - final List messageIds = new ArrayList((List) providedObject.get("messages")); - QueueEntryTransaction txn = - isMoveTransaction - ? new MoveTransaction(sourceQueue, messageIds, destinationQueue) - : new CopyTransaction(sourceQueue, messageIds, destinationQueue); - vhost.executeTransaction(txn); - response.setStatus(HttpServletResponse.SC_OK); - - } - catch(AccessControlException e) - { - response.setStatus(HttpServletResponse.SC_FORBIDDEN); - } - catch(RuntimeException e) - { - LOGGER.error("Failure to perform message operation", e); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - } - - /* - * DELETE removes specified messages from, or clears the queue - */ - @Override - protected void doDeleteWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - final Queue queue = getQueueFromRequest(request); - - final VirtualHost vhost = queue.getParent(VirtualHost.class); - boolean clearQueue = Boolean.parseBoolean(request.getParameter("clear")); - - try - { - if (clearQueue) - { - clearQueue(queue, vhost); - } - else - { - final List messageIds = new ArrayList<>(); - for(String idStr : request.getParameterValues("id")) - { - messageIds.add(Long.valueOf(idStr)); - } - - deleteMessages(queue, vhost, messageIds); - } - response.setStatus(HttpServletResponse.SC_OK); - } - catch (AccessControlException e) - { - response.setStatus(HttpServletResponse.SC_FORBIDDEN); - } - - } - - private void deleteMessages(final Queue queue, final VirtualHost vhost, final List messageIds) - { - // FIXME: added temporary authorization check until we introduce management layer - // and review current ACL rules to have common rules for all management interfaces - authorizeMethod("deleteMessages", vhost); - vhost.executeTransaction(new DeleteTransaction(queue, messageIds)); - } - - private void clearQueue(final Queue queue, final VirtualHost vhost) - { - // FIXME: added temporary authorization check until we introduce management layer - // and review current ACL rules to have common rules for all management interfaces - authorizeMethod("clearQueue", vhost); - vhost.executeTransaction(new ClearQueueTransaction(queue)); - } - - private void authorizeMethod(String methodName, VirtualHost vhost) - { - SecurityManager securityManager = getBroker().getSecurityManager(); - securityManager.authoriseMethod(Operation.UPDATE, "VirtualHost.Queue", methodName, vhost.getName()); - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MetaDataServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MetaDataServlet.java deleted file mode 100644 index 88705563af..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/MetaDataServlet.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.server.management.plugin.servlet.rest; - -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; - -import org.apache.qpid.server.model.BrokerModel; -import org.apache.qpid.server.model.ConfiguredAutomatedAttribute; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.ConfiguredObjectAttribute; -import org.apache.qpid.server.model.ConfiguredObjectTypeRegistry; -import org.apache.qpid.server.model.ManagedObject; -import org.apache.qpid.server.model.Model; - -public class MetaDataServlet extends AbstractServlet -{ - - private Model _instance; - - public MetaDataServlet(final Model model) - { - _instance = model; - } - - @Override - public void init() throws ServletException - { - super.init(); - } - - - - @Override - protected void doGetWithSubjectAndActor(final HttpServletRequest request, final HttpServletResponse response) - throws ServletException, IOException - { - response.setContentType("application/json"); - response.setStatus(HttpServletResponse.SC_OK); - - Map classToDataMap = new TreeMap<>(); - - for(Class clazz : _instance.getSupportedCategories()) - { - classToDataMap.put(clazz.getSimpleName(), processCategory(clazz)); - } - - final Writer writer = getOutputWriter(request, response); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, classToDataMap); - - response.setContentType("application/json"); - response.setStatus(HttpServletResponse.SC_OK); - - } - - private Map processCategory(final Class clazz) - { - Map typeToDataMap = new TreeMap<>(); - ConfiguredObjectTypeRegistry typeRegistry = _instance.getTypeRegistry(); - for(Class type : typeRegistry.getTypeSpecialisations(clazz)) - { - typeToDataMap.put(ConfiguredObjectTypeRegistry.getType(type), processType(type)); - } - return typeToDataMap; - } - - private Map processType(final Class type) - { - Map typeDetails = new LinkedHashMap<>(); - typeDetails.put("attributes", processAttributes(type)); - typeDetails.put("managedInterfaces", getManagedInterfaces(type)); - typeDetails.put("validChildTypes", getValidChildTypes(type)); - ManagedObject annotation = type.getAnnotation(ManagedObject.class); - if(annotation != null) - { - if(annotation.deprecated()) - { - typeDetails.put("deprecated",true); - } - if(!"".equals(annotation.description() ) ) - { - typeDetails.put("description", annotation.description()); - } - } - return typeDetails; - } - - private Map> getValidChildTypes(final Class type) - { - Map> validChildTypes = new HashMap<>(); - for(Class childType : _instance.getChildTypes(ConfiguredObjectTypeRegistry.getCategory(type))) - { - Collection validValues = _instance.getTypeRegistry().getValidChildTypes(type, childType); - if(validValues != null) - { - validChildTypes.put(childType.getSimpleName(), validValues); - } - } - return validChildTypes; - } - - private Set getManagedInterfaces(Class type) - { - Set interfaces = new HashSet<>(); - for(Class classObject: _instance.getTypeRegistry().getManagedInterfaces(type)) - { - interfaces.add(classObject.getSimpleName()); - } - return interfaces; - } - - private Map processAttributes(final Class type) - { - Collection> attributes = - _instance.getTypeRegistry().getAttributeTypes(type).values(); - - Map attributeDetails = new LinkedHashMap<>(); - for(ConfiguredObjectAttribute attribute : attributes) - { - Map attrDetails = new LinkedHashMap<>(); - attrDetails.put("type",attribute.getType().getSimpleName()); - if(!"".equals(attribute.getDescription())) - { - attrDetails.put("description",attribute.getDescription()); - } - if(attribute.isDerived()) - { - attrDetails.put("derived",attribute.isDerived()); - } - if(attribute.isAutomated()) - { - if(!"".equals(((ConfiguredAutomatedAttribute)attribute).defaultValue())) - { - attrDetails.put("defaultValue",((ConfiguredAutomatedAttribute)attribute).defaultValue()); - } - if(((ConfiguredAutomatedAttribute)attribute).isMandatory()) - { - attrDetails.put("mandatory",((ConfiguredAutomatedAttribute)attribute).isMandatory()); - } - if(!(((ConfiguredAutomatedAttribute)attribute).validValues()).isEmpty()) - { - Collection validValues = ((ConfiguredAutomatedAttribute) attribute).validValues(); - - Collection convertedValues = new ArrayList<>(validValues.size()); - for(String value : validValues) - { - convertedValues.add(attribute.convert(value,null)); - } - attrDetails.put("validValues", convertedValues); - } - - } - if(attribute.isSecure()) - { - attrDetails.put("secure",attribute.isSecure()); - } - if(attribute.isOversized()) - { - attrDetails.put("oversize", attribute.isOversized()); - } - attributeDetails.put(attribute.getName(), attrDetails); - } - return attributeDetails; - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/PluginClassProviderAction.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/PluginClassProviderAction.java deleted file mode 100644 index cd14abc582..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/PluginClassProviderAction.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.apache.qpid.server.management.plugin.servlet.rest;/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT 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.List; -import java.util.Map; - -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.plugin.Pluggable; -import org.apache.qpid.server.plugin.QpidServiceLoader; - -public class PluginClassProviderAction implements Action -{ - @Override - public String getName() - { - return "pluginList"; - } - - @Override - public Object perform(Map request, Broker broker) - { - try - { - String className = (String) request.get("plugin"); - QpidServiceLoader serviceLoader = new QpidServiceLoader(); - final Class clazz = (Class) Class.forName("org.apache.qpid.server.plugin."+className); - List values = new ArrayList(); - for(Pluggable instance : serviceLoader.instancesOf(clazz)) - { - values.add(instance.getType()); - } - return values; - } - catch (ClassNotFoundException e) - { - return Collections.emptyList(); - } - - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/QueueReportServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/QueueReportServlet.java deleted file mode 100644 index 2b3def2dab..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/QueueReportServlet.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.management.plugin.servlet.rest; - -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.qpid.server.management.plugin.report.ReportRunner; -import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.VirtualHost; - -public class QueueReportServlet extends AbstractServlet -{ - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws - IOException, - ServletException - { - String[] pathInfoElements = getPathInfoElements(request); - if(pathInfoElements != null && pathInfoElements.length == 3) - { - Queue queue = getQueueFromRequest(request); - ReportRunner reportRunner = ReportRunner.createRunner(pathInfoElements[2],request.getParameterMap()); - Object output = reportRunner.runReport(queue); - response.setContentType(reportRunner.getContentType()); - if(reportRunner.isBinaryReport()) - { - response.getOutputStream().write((byte[])output); - } - else - { - response.getWriter().write((String)output); - } - } - else - { - throw new IllegalArgumentException("Invalid path is specified"); - } - - } - - private Queue getQueueFromRequest(HttpServletRequest request) - { - String[] pathInfoElements = getPathInfoElements(request); - if(pathInfoElements == null || pathInfoElements.length < 2) - { - throw new IllegalArgumentException("Invalid path is specified"); - } - String vhostName = pathInfoElements[0]; - String queueName = pathInfoElements[1]; - - VirtualHost vhost = getBroker().findVirtualHostByName(vhostName); - if (vhost == null) - { - throw new IllegalArgumentException("Could not find virtual host with name '" + vhostName + "'"); - } - - Queue queueFromVirtualHost = getQueueFromVirtualHost(queueName, vhost); - if (queueFromVirtualHost == null) - { - throw new IllegalArgumentException("Could not find queue with name '" + queueName + "' on virtual host '" + vhost.getName() + "'"); - } - return queueFromVirtualHost; - } - - private Queue getQueueFromVirtualHost(String queueName, VirtualHost vhost) - { - Queue queue = null; - - for(Queue q : vhost.getQueues()) - { - - if(q.getName().equals(queueName)) - { - queue = q; - break; - } - } - return queue; - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/RestServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/RestServlet.java deleted file mode 100644 index 275d7f6794..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/RestServlet.java +++ /dev/null @@ -1,774 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - *

- * http://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.plugin.servlet.rest; - -import java.io.IOException; -import java.io.Writer; -import java.security.AccessControlException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.Part; - -import org.apache.qpid.server.model.AbstractConfiguredObject; -import org.apache.qpid.server.model.IllegalStateTransitionException; -import org.apache.qpid.server.model.IntegrityViolationException; -import org.apache.qpid.server.virtualhost.ExchangeExistsException; -import org.apache.qpid.server.virtualhost.QueueExistsException; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.util.urlstreamhandler.data.Handler; -import org.apache.qpid.util.DataUrlUtils; - -public class RestServlet extends AbstractServlet -{ - private static final Logger LOGGER = LoggerFactory.getLogger(RestServlet.class); - /** - * An initialization parameter to specify hierarchy - */ - private static final String HIERARCHY_INIT_PARAMETER = "hierarchy"; - - public static final String DEPTH_PARAM = "depth"; - public static final String OVERSIZE_PARAM = "oversize"; - public static final String ACTUALS_PARAM = "actuals"; - public static final String SORT_PARAM = "sort"; - public static final String INCLUDE_SYS_CONTEXT_PARAM = "includeSysContext"; - public static final String INHERITED_ACTUALS_PARAM = "inheritedActuals"; - public static final String EXTRACT_INITIAL_CONFIG_PARAM = "extractInitialConfig"; - public static final int SC_UNPROCESSABLE_ENTITY = 422; - - /** - * Signifies that the agent wishes the servlet to set the Content-Disposition on the - * response with the value attachment. This filename will be derived from the parameter value. - */ - public static final String CONTENT_DISPOSITION_ATTACHMENT_FILENAME_PARAM = "contentDispositionAttachmentFilename"; - - public static final Set RESERVED_PARAMS = - new HashSet<>(Arrays.asList(DEPTH_PARAM, - SORT_PARAM, - OVERSIZE_PARAM, - ACTUALS_PARAM, - INCLUDE_SYS_CONTEXT_PARAM, - EXTRACT_INITIAL_CONFIG_PARAM, - INHERITED_ACTUALS_PARAM, - CONTENT_DISPOSITION_ATTACHMENT_FILENAME_PARAM)); - - private Class[] _hierarchy; - - private final ConfiguredObjectToMapConverter _objectConverter = new ConfiguredObjectToMapConverter(); - private final boolean _hierarchyInitializationRequired; - - public RestServlet() - { - super(); - _hierarchyInitializationRequired = true; - } - - public RestServlet(Class... hierarchy) - { - super(); - _hierarchy = hierarchy; - _hierarchyInitializationRequired = false; - } - - @Override - public void init() throws ServletException - { - super.init(); - if (_hierarchyInitializationRequired) - { - doInitialization(); - } - Handler.register(); - } - - @SuppressWarnings("unchecked") - private void doInitialization() throws ServletException - { - ServletConfig config = getServletConfig(); - String hierarchy = config.getInitParameter(HIERARCHY_INIT_PARAMETER); - if (hierarchy != null && !"".equals(hierarchy)) - { - List> classes = new ArrayList>(); - String[] hierarchyItems = hierarchy.split(","); - for (String item : hierarchyItems) - { - Class itemClass = null; - try - { - itemClass = Class.forName(item); - } - catch (ClassNotFoundException e) - { - try - { - itemClass = Class.forName("org.apache.qpid.server.model." + item); - } - catch (ClassNotFoundException e1) - { - throw new ServletException("Unknown configured object class '" + item - + "' is specified in hierarchy for " + config.getServletName()); - } - } - Class clazz = (Class)itemClass; - classes.add(clazz); - } - Class[] hierarchyClasses = (Class[])new Class[classes.size()]; - _hierarchy = classes.toArray(hierarchyClasses); - } - else - { - _hierarchy = (Class[])new Class[0]; - } - } - - protected Collection> getObjects(HttpServletRequest request) - { - String[] pathInfoElements = getPathInfoElements(request); - List names = new ArrayList(); - if(pathInfoElements != null) - { - if(pathInfoElements.length > _hierarchy.length) - { - throw new IllegalArgumentException("Too many entries in path for REST servlet " - + getServletName() + ". Expected hierarchy length: " + _hierarchy.length - + "; Request hierarchy length: " + pathInfoElements.length - + "; Path Elements: " + Arrays.toString(pathInfoElements)); - } - names.addAll(Arrays.asList(pathInfoElements)); - } - - Collection> parents = new ArrayList>(); - parents.add(getBroker()); - Collection> children = new ArrayList>(); - - Map, String> filters = - new HashMap, String>(); - - for(int i = 0; i < _hierarchy.length; i++) - { - if(i == 0 || getBroker().getModel().getChildTypes(_hierarchy[i - 1]).contains(_hierarchy[i])) - { - - for(ConfiguredObject parent : parents) - { - if(names.size() > i - && names.get(i) != null - && !names.get(i).equals("*") - && names.get(i).trim().length() != 0) - { - for(ConfiguredObject child : parent.getChildren(_hierarchy[i])) - { - if(child.getName().equals(names.get(i))) - { - children.add(child); - } - } - } - else - { - children.addAll((Collection>) parent.getChildren(_hierarchy[i])); - } - } - } - else - { - children = parents; - if(names.size() > i - && names.get(i) != null - && !names.get(i).equals("*") - && names.get(i).trim().length() != 0) - { - filters.put(_hierarchy[i], names.get(i)); - } - } - - parents = children; - children = new ArrayList>(); - } - - if(!filters.isEmpty()) - { - Collection> potentials = parents; - parents = new ArrayList>(); - - for(ConfiguredObject o : potentials) - { - - boolean match = true; - - for(Map.Entry, String> entry : filters.entrySet()) - { - Collection ancestors = - getAncestors(getConfiguredClass(),entry.getKey(), o); - match = false; - for(ConfiguredObject ancestor : ancestors) - { - if(ancestor.getName().equals(entry.getValue())) - { - match = true; - break; - } - } - if(!match) - { - break; - } - } - if(match) - { - parents.add(o); - } - - } - } - - return filter(parents, request); - } - - private Collection> filter(Collection> objects, HttpServletRequest request) - { - - - Map> filters = new HashMap>(); - - for(String param : (Collection) Collections.list(request.getParameterNames())) - { - if(!RESERVED_PARAMS.contains(param)) - { - filters.put(param, Arrays.asList(request.getParameterValues(param))); - } - } - - if(filters.isEmpty()) - { - return objects; - } - - Collection> filteredObj = new ArrayList>(objects); - - Iterator> iter = filteredObj.iterator(); - - while(iter.hasNext()) - { - ConfiguredObject obj = iter.next(); - for(Map.Entry> entry : filters.entrySet()) - { - Object value = obj.getAttribute(entry.getKey()); - if(!entry.getValue().contains(String.valueOf(value))) - { - iter.remove(); - } - } - - } - - return filteredObj; - } - - private Collection getAncestors(Class childType, - Class ancestorType, - ConfiguredObject child) - { - Collection ancestors = new HashSet(); - Collection> parentTypes = child.getModel().getParentTypes(childType); - - for(Class parentClazz : parentTypes) - { - if(parentClazz == ancestorType) - { - ConfiguredObject parent = child.getParent(parentClazz); - if(parent != null) - { - ancestors.add(parent); - } - } - else - { - ConfiguredObject parent = child.getParent(parentClazz); - if(parent != null) - { - ancestors.addAll(getAncestors(parentClazz, ancestorType, parent)); - } - } - } - - return ancestors; - } - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - // TODO - sort special params, everything else should act as a filter - String attachmentFilename = request.getParameter(CONTENT_DISPOSITION_ATTACHMENT_FILENAME_PARAM); - boolean extractInitialConfig = getBooleanParameterFromRequest(request, EXTRACT_INITIAL_CONFIG_PARAM); - - response.setContentType("application/json"); - response.setStatus(HttpServletResponse.SC_OK); - - if (attachmentFilename == null) - { - setCachingHeadersOnResponse(response); - } - else - { - setContentDispositionHeaderIfNecessary(response, attachmentFilename); - } - - Collection> allObjects = getObjects(request); - - int depth; - boolean actuals; - boolean includeSystemContext; - boolean inheritedActuals; - int oversizeThreshold; - - if(extractInitialConfig) - { - depth = Integer.MAX_VALUE; - oversizeThreshold = Integer.MAX_VALUE; - actuals = true; - includeSystemContext = false; - inheritedActuals = false; - } - else - { - depth = getIntParameterFromRequest(request, DEPTH_PARAM, 1); - oversizeThreshold = getIntParameterFromRequest(request, OVERSIZE_PARAM, 120); - actuals = getBooleanParameterFromRequest(request, ACTUALS_PARAM); - includeSystemContext = getBooleanParameterFromRequest(request, INCLUDE_SYS_CONTEXT_PARAM); - inheritedActuals = getBooleanParameterFromRequest(request, INHERITED_ACTUALS_PARAM); - } - - List> output = new ArrayList<>(); - for(ConfiguredObject configuredObject : allObjects) - { - - output.add(_objectConverter.convertObjectToMap(configuredObject, getConfiguredClass(), - depth, actuals, inheritedActuals, includeSystemContext, extractInitialConfig, oversizeThreshold, request.isSecure())); - } - - - Writer writer = getOutputWriter(request, response); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, extractInitialConfig && output.size() == 1 ? output.get(0) : output); - } - - private void setContentDispositionHeaderIfNecessary(final HttpServletResponse response, - final String attachmentFilename) - { - if (attachmentFilename != null) - { - String filenameRfc2183 = ensureFilenameIsRfc2183(attachmentFilename); - if (filenameRfc2183.length() > 0) - { - response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filenameRfc2183)); - } - else - { - response.setHeader("Content-disposition", String.format("attachment")); // Agent will allow user to choose a name - } - } - } - - private Class getConfiguredClass() - { - return _hierarchy.length == 0 ? Broker.class : _hierarchy[_hierarchy.length-1]; - } - - @Override - protected void doPutWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - performCreateOrUpdate(request, response); - } - - private void performCreateOrUpdate(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException - { - response.setContentType("application/json"); - - List names = getParentNamesFromServletPath(request); - Map providedObject = getRequestProvidedObject(request); - boolean isFullObjectURL = names.size() == _hierarchy.length; - boolean updateOnlyAllowed = isFullObjectURL && "POST".equalsIgnoreCase(request.getMethod()); - try - { - if (names.isEmpty() && _hierarchy.length == 0) - { - getBroker().setAttributes(providedObject); - response.setStatus(HttpServletResponse.SC_OK); - return; - } - - ConfiguredObject theParent = getBroker(); - ConfiguredObject[] otherParents = null; - Class objClass = getConfiguredClass(); - if (_hierarchy.length > 1) - { - List parents = findAllObjectParents(names); - theParent = parents.remove(0); - otherParents = parents.toArray(new ConfiguredObject[parents.size()]); - } - - if (isFullObjectURL) - { - providedObject.put("name", names.get(names.size() - 1)); - ConfiguredObject configuredObject = findObjectToUpdateInParent(objClass, providedObject, theParent, otherParents); - - if (configuredObject != null) - { - configuredObject.setAttributes(providedObject); - response.setStatus(HttpServletResponse.SC_OK); - return; - } - else if (updateOnlyAllowed) - { - sendErrorResponse(request, response, HttpServletResponse.SC_NOT_FOUND, "Object with " - + (providedObject.containsKey("id") ? " id '" + providedObject.get("id") : " name '" + providedObject.get("name")) - + "' does not exist!"); - return; - } - } - - ConfiguredObject configuredObject = theParent.createChild(objClass, providedObject, otherParents); - StringBuffer requestURL = request.getRequestURL(); - if (!isFullObjectURL) - { - requestURL.append("/").append(configuredObject.getName()); - } - response.setHeader("Location", requestURL.toString()); - response.setStatus(HttpServletResponse.SC_CREATED); - } - catch (RuntimeException e) - { - setResponseStatus(request, response, e); - } - - } - - private List findAllObjectParents(List names) - { - Collection[] objects = new Collection[_hierarchy.length]; - for (int i = 0; i < _hierarchy.length - 1; i++) - { - objects[i] = new HashSet<>(); - if (i == 0) - { - for (ConfiguredObject object : getBroker().getChildren(_hierarchy[0])) - { - if (object.getName().equals(names.get(0))) - { - objects[0].add(object); - break; - } - } - } - else - { - for (int j = i - 1; j >= 0; j--) - { - if (getBroker().getModel().getChildTypes(_hierarchy[j]).contains(_hierarchy[i])) - { - for (ConfiguredObject parent : objects[j]) - { - for (ConfiguredObject object : parent.getChildren(_hierarchy[i])) - { - if (object.getName().equals(names.get(i))) - { - objects[i].add(object); - } - } - } - break; - } - } - } - - } - List parents = new ArrayList<>(); - Class objClass = getConfiguredClass(); - Collection> parentClasses = - getBroker().getModel().getParentTypes(objClass); - for (int i = _hierarchy.length - 2; i >= 0; i--) - { - if (parentClasses.contains(_hierarchy[i])) - { - if (objects[i].size() == 1) - { - parents.add(objects[i].iterator().next()); - } - else - { - throw new IllegalArgumentException("Cannot deduce parent of class " - + _hierarchy[i].getSimpleName()); - } - } - - } - return parents; - } - - private List getParentNamesFromServletPath(HttpServletRequest request) - { - List names = new ArrayList<>(); - String[] pathInfoElements = getPathInfoElements(request); - if (pathInfoElements != null) - { - if (!(pathInfoElements.length == _hierarchy.length || - (_hierarchy.length > 0 && pathInfoElements.length == _hierarchy.length - 1))) - { - throw new IllegalArgumentException("Either parent path or full object path must be specified on object creation." - + " Full object path must be specified on object update. " - + "Found " - + names - + " of size " - + names.size() - + " expecting " - + _hierarchy.length); - } - names.addAll(Arrays.asList(pathInfoElements)); - } - return names; - } - - private Map getRequestProvidedObject(HttpServletRequest request) throws IOException, ServletException - { - Map providedObject; - - ArrayList headers = Collections.list(request.getHeaderNames()); - ObjectMapper mapper = new ObjectMapper(); - - if(headers.contains("Content-Type") && request.getHeader("Content-Type").startsWith("multipart/form-data")) - { - providedObject = new HashMap<>(); - Map fileUploads = new HashMap<>(); - Collection parts = request.getParts(); - for(Part part : parts) - { - if("data".equals(part.getName()) && "application/json".equals(part.getContentType())) - { - providedObject = mapper.readValue(part.getInputStream(), LinkedHashMap.class); - } - else - { - byte[] data = new byte[(int) part.getSize()]; - part.getInputStream().read(data); - String inlineURL = DataUrlUtils.getDataUrlForBytes(data); - fileUploads.put(part.getName(),inlineURL.toString()); - } - } - providedObject.putAll(fileUploads); - } - else - { - - providedObject = mapper.readValue(request.getInputStream(), LinkedHashMap.class); - } - return providedObject; - } - - private ConfiguredObject findObjectToUpdateInParent(Class objClass, Map providedObject, ConfiguredObject theParent, ConfiguredObject[] otherParents) - { - Collection existingChildren = theParent.getChildren(objClass); - - for (ConfiguredObject obj : existingChildren) - { - if ((providedObject.containsKey("id") && String.valueOf(providedObject.get("id")).equals(obj.getId().toString())) - || (obj.getName().equals(providedObject.get("name")) && sameOtherParents(obj, otherParents, objClass))) - { - return obj; - } - } - return null; - } - - private boolean sameOtherParents(ConfiguredObject obj, ConfiguredObject[] otherParents, Class objClass) - { - Collection> parentClasses = obj.getModel().getParentTypes(objClass); - - if(otherParents == null || otherParents.length == 0) - { - return parentClasses.size() == 1; - } - - - for (ConfiguredObject parent : otherParents) - { - boolean found = false; - for (Class parentClass : parentClasses) - { - if (parent == obj.getParent(parentClass)) - { - found = true; - break; - } - } - - if (!found) - { - return false; - } - } - - return true; - } - - private void setResponseStatus(HttpServletRequest request, HttpServletResponse response, RuntimeException e) throws IOException - { - if (e instanceof AccessControlException) - { - if (LOGGER.isDebugEnabled()) - { - LOGGER.debug("AccessControlException, sending " + HttpServletResponse.SC_FORBIDDEN, e); - } - response.setStatus(HttpServletResponse.SC_FORBIDDEN); - } - else - { - int responseCode = HttpServletResponse.SC_BAD_REQUEST; - String message = e.getMessage(); - if (e instanceof ExchangeExistsException || e instanceof QueueExistsException - || e instanceof AbstractConfiguredObject.DuplicateIdException - || e instanceof AbstractConfiguredObject.DuplicateNameException - || e instanceof IntegrityViolationException - || e instanceof IllegalStateTransitionException) - { - responseCode = HttpServletResponse.SC_CONFLICT; - } - else if (e instanceof IllegalConfigurationException || e instanceof IllegalArgumentException) - { - if (LOGGER.isDebugEnabled()) - { - LOGGER.debug(e.getClass().getSimpleName() + " processing request : " + message); - } - else if (LOGGER.isTraceEnabled()) - { - LOGGER.trace(e.getClass().getSimpleName() + " processing request", e); - } - responseCode = SC_UNPROCESSABLE_ENTITY; - } - else - { - LOGGER.warn("Unexpected exception processing request ", e); - } - - - sendErrorResponse(request, response, responseCode, message); - - } - } - - private void sendErrorResponse(HttpServletRequest request, HttpServletResponse response, int responseCode, String message) throws IOException - { - response.setStatus(responseCode); - - response.setContentType("application/json"); - response.setCharacterEncoding("UTF-8"); - - Writer out = getOutputWriter(request, response); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(out, Collections.singletonMap("errorMessage", message)); - } - - @Override - protected void doDeleteWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - response.setContentType("application/json"); - response.setStatus(HttpServletResponse.SC_OK); - - setCachingHeadersOnResponse(response); - try - { - Collection> allObjects = getObjects(request); - for(ConfiguredObject o : allObjects) - { - o.delete(); - } - - response.setStatus(HttpServletResponse.SC_OK); - } - catch(RuntimeException e) - { - setResponseStatus(request, response, e); - } - } - - @Override - protected void doPostWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - performCreateOrUpdate(request, response); - } - - private void setCachingHeadersOnResponse(HttpServletResponse response) - { - response.setHeader("Cache-Control","no-cache"); - response.setHeader("Pragma","no-cache"); - response.setDateHeader ("Expires", 0); - } - - private int getIntParameterFromRequest(final HttpServletRequest request, - final String paramName, - final int defaultValue) - { - int intValue = defaultValue; - final String stringValue = request.getParameter(paramName); - if(stringValue!=null) - { - try - { - intValue = Integer.parseInt(stringValue); - } - catch (NumberFormatException e) - { - LOGGER.warn("Could not parse " + stringValue + " as integer for parameter " + paramName); - } - } - return intValue; - } - - private boolean getBooleanParameterFromRequest(HttpServletRequest request, final String paramName) - { - return Boolean.parseBoolean(request.getParameter(paramName)); - } - - private String ensureFilenameIsRfc2183(final String requestedFilename) - { - String fileNameRfc2183 = requestedFilename.replaceAll("[\\P{InBasic_Latin}\\\\:/]", ""); - return fileNameRfc2183; - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/SaslServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/SaslServlet.java deleted file mode 100644 index 5bff0e22e5..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/SaslServlet.java +++ /dev/null @@ -1,319 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * 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.plugin.servlet.rest; - -import java.io.IOException; -import java.io.Writer; -import java.net.SocketAddress; -import java.security.Principal; -import java.security.SecureRandom; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; - -import javax.security.auth.Subject; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.apache.commons.codec.binary.Base64; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.management.plugin.HttpManagementConfiguration; -import org.apache.qpid.server.management.plugin.HttpManagementUtil; -import org.apache.qpid.server.management.plugin.servlet.ServletConnectionPrincipal; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.security.SubjectCreator; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; -import org.apache.qpid.server.util.ConnectionScopedRuntimeException; - -public class SaslServlet extends AbstractServlet -{ - - private static final Logger LOGGER = LoggerFactory.getLogger(SaslServlet.class); - - private static final SecureRandom SECURE_RANDOM = new SecureRandom(); - private static final String ATTR_RANDOM = "SaslServlet.Random"; - private static final String ATTR_ID = "SaslServlet.ID"; - private static final String ATTR_SASL_SERVER = "SaslServlet.SaslServer"; - private static final String ATTR_EXPIRY = "SaslServlet.Expiry"; - private static final long SASL_EXCHANGE_EXPIRY = 3000L; - - public SaslServlet() - { - super(); - } - - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws - ServletException, - IOException - { - response.setContentType("application/json"); - response.setStatus(HttpServletResponse.SC_OK); - - response.setHeader("Cache-Control","no-cache"); - response.setHeader("Pragma","no-cache"); - response.setDateHeader ("Expires", 0); - - HttpSession session = request.getSession(); - getRandom(session); - - SubjectCreator subjectCreator = getSubjectCreator(request); - List mechanismsList = subjectCreator.getMechanisms(); - String[] mechanisms = mechanismsList.toArray(new String[mechanismsList.size()]); - Map outputObject = new LinkedHashMap(); - - final Subject subject = getAuthorisedSubject(request); - if(subject != null) - { - Principal principal = AuthenticatedPrincipal.getAuthenticatedPrincipalFromSubject(subject); - outputObject.put("user", principal.getName()); - } - else if (request.getRemoteUser() != null) - { - outputObject.put("user", request.getRemoteUser()); - } - - outputObject.put("mechanisms", (Object) mechanisms); - - final Writer writer = getOutputWriter(request, response); - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, outputObject); - - } - - private Random getRandom(final HttpSession session) - { - Random rand = (Random) session.getAttribute(ATTR_RANDOM); - if(rand == null) - { - synchronized (SECURE_RANDOM) - { - rand = new Random(SECURE_RANDOM.nextLong()); - } - session.setAttribute(ATTR_RANDOM, rand); - } - return rand; - } - - - @Override - protected void doPostWithSubjectAndActor(final HttpServletRequest request, final HttpServletResponse response) throws IOException - { - checkSaslAuthEnabled(request); - - try - { - response.setContentType("application/json"); - response.setHeader("Cache-Control","no-cache"); - response.setHeader("Pragma","no-cache"); - response.setDateHeader("Expires", 0); - - HttpSession session = request.getSession(); - - String mechanism = request.getParameter("mechanism"); - String id = request.getParameter("id"); - String saslResponse = request.getParameter("response"); - - SubjectCreator subjectCreator = getSubjectCreator(request); - - if(mechanism != null) - { - if(id == null) - { - if(LOGGER.isDebugEnabled()) - { - LOGGER.debug("Creating SaslServer for mechanism: " + mechanism); - } - SaslServer saslServer = subjectCreator.createSaslServer(mechanism, request.getServerName(), null/*TODO*/); - evaluateSaslResponse(request, response, session, saslResponse, saslServer, subjectCreator); - } - else - { - response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED); - session.removeAttribute(ATTR_ID); - session.removeAttribute(ATTR_SASL_SERVER); - session.removeAttribute(ATTR_EXPIRY); - } - } - else - { - if(id != null) - { - if(id.equals(session.getAttribute(ATTR_ID)) && System.currentTimeMillis() < (Long) session.getAttribute(ATTR_EXPIRY)) - { - SaslServer saslServer = (SaslServer) session.getAttribute(ATTR_SASL_SERVER); - evaluateSaslResponse(request, response, session, saslResponse, saslServer, subjectCreator); - } - else - { - response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED); - session.removeAttribute(ATTR_ID); - session.removeAttribute(ATTR_SASL_SERVER); - session.removeAttribute(ATTR_EXPIRY); - } - } - else - { - response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED); - session.removeAttribute(ATTR_ID); - session.removeAttribute(ATTR_SASL_SERVER); - session.removeAttribute(ATTR_EXPIRY); - } - } - } - catch(IOException e) - { - LOGGER.error("Error processing SASL request", e); - throw e; - } - catch(RuntimeException e) - { - LOGGER.error("Error processing SASL request", e); - throw e; - } - } - - private void checkSaslAuthEnabled(HttpServletRequest request) - { - boolean saslAuthEnabled = false; - HttpManagementConfiguration management = getManagementConfiguration(); - if (request.isSecure()) - { - saslAuthEnabled = management.isHttpsSaslAuthenticationEnabled(); - } - else - { - saslAuthEnabled = management.isHttpSaslAuthenticationEnabled(); - } - if (!saslAuthEnabled) - { - throw new ConnectionScopedRuntimeException("Sasl authentication disabled."); - } - } - - private void evaluateSaslResponse(final HttpServletRequest request, - final HttpServletResponse response, - final HttpSession session, final String saslResponse, final SaslServer saslServer, SubjectCreator subjectCreator) throws IOException - { - final String id; - byte[] challenge; - try - { - challenge = saslServer.evaluateResponse(saslResponse == null ? new byte[0] : Base64.decodeBase64(saslResponse.getBytes())); - } - catch(SaslException e) - { - session.removeAttribute(ATTR_ID); - session.removeAttribute(ATTR_SASL_SERVER); - session.removeAttribute(ATTR_EXPIRY); - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - - return; - } - - if(saslServer.isComplete()) - { - Subject originalSubject = subjectCreator.createSubjectWithGroups(new AuthenticatedPrincipal(saslServer.getAuthorizationID())); - Subject subject = new Subject(false, - originalSubject.getPrincipals(), - originalSubject.getPublicCredentials(), - originalSubject.getPrivateCredentials()); - subject.getPrincipals().add(new ServletConnectionPrincipal(request)); - subject.setReadOnly(); - - Broker broker = getBroker(); - try - { - HttpManagementUtil.assertManagementAccess(broker.getSecurityManager(), subject); - } - catch(SecurityException e) - { - sendError(response, HttpServletResponse.SC_FORBIDDEN); - return; - } - - HttpManagementUtil.saveAuthorisedSubject(request.getSession(), subject); - session.removeAttribute(ATTR_ID); - session.removeAttribute(ATTR_SASL_SERVER); - session.removeAttribute(ATTR_EXPIRY); - if(challenge != null && challenge.length != 0) - { - Map outputObject = new LinkedHashMap(); - outputObject.put("challenge", new String(Base64.encodeBase64(challenge))); - - final Writer writer = getOutputWriter(request, response); - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, outputObject); - } - response.setStatus(HttpServletResponse.SC_OK); - } - else - { - Random rand = getRandom(session); - id = String.valueOf(rand.nextLong()); - session.setAttribute(ATTR_ID, id); - session.setAttribute(ATTR_SASL_SERVER, saslServer); - session.setAttribute(ATTR_EXPIRY, System.currentTimeMillis() + SASL_EXCHANGE_EXPIRY); - - response.setStatus(HttpServletResponse.SC_OK); - - Map outputObject = new LinkedHashMap(); - outputObject.put("id", id); - outputObject.put("challenge", new String(Base64.encodeBase64(challenge))); - - final Writer writer = getOutputWriter(request, response); - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, outputObject); - } - } - - private SubjectCreator getSubjectCreator(HttpServletRequest request) - { - return HttpManagementUtil.getManagementConfiguration(getServletContext()).getAuthenticationProvider(request).getSubjectCreator( - request.isSecure()); - } - - @Override - protected Subject getAuthorisedSubject(HttpServletRequest request) - { - Subject subject = HttpManagementUtil.getAuthorisedSubject(request.getSession()); - if(subject == null) - { - subject = HttpManagementUtil.tryToAuthenticate(request, HttpManagementUtil.getManagementConfiguration(getServletContext())); - } - return subject; - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/StructureServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/StructureServlet.java deleted file mode 100644 index 7508aa2d0b..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/StructureServlet.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.management.plugin.servlet.rest; - -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; - -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; - -public class StructureServlet extends AbstractServlet -{ - public StructureServlet() - { - super(); - } - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException - { - response.setContentType("application/json"); - response.setStatus(HttpServletResponse.SC_OK); - - response.setHeader("Cache-Control","no-cache"); - response.setHeader("Pragma","no-cache"); - response.setDateHeader ("Expires", 0); - - // TODO filtering??? request.getParameter("filter"); // filter=1,2,3 /groups/*/* - - Map structure = generateStructure(getBroker(), Broker.class); - - final Writer writer = getOutputWriter(request, response); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - mapper.writeValue(writer, structure); - - response.setStatus(HttpServletResponse.SC_OK); - - } - - private Map generateStructure(ConfiguredObject object, Class clazz) - { - Map structure = new LinkedHashMap(); - structure.put("id", object.getId()); - structure.put("name", object.getName()); - - for(Class childClass : object.getModel().getChildTypes(clazz)) - { - Collection children = object.getChildren(childClass); - if(children != null) - { - List> childObjects = new ArrayList>(); - - for(ConfiguredObject child : children) - { - childObjects.add(generateStructure(child, childClass)); - } - - if(!childObjects.isEmpty()) - { - structure.put(pluralize(childClass),childObjects); - } - } - } - - return structure; - } - - private String pluralize(Class childClass) - { - String name = childClass.getSimpleName().toLowerCase(); - return name + (name.endsWith("s") ? "es" : "s"); - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/UserPreferencesServlet.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/UserPreferencesServlet.java deleted file mode 100644 index bbaecca017..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/UserPreferencesServlet.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.server.management.plugin.servlet.rest; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.PreferencesProvider; -import org.apache.qpid.server.model.User; -import org.apache.qpid.server.security.access.Operation; - -public class UserPreferencesServlet extends AbstractServlet -{ - private static final Logger LOGGER = LoggerFactory.getLogger(UserPreferencesServlet.class); - private static final long serialVersionUID = 1L; - - @Override - protected void doGetWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws IOException, - ServletException - { - String[] pathElements = getPathInfoElements(request); - if (pathElements != null && pathElements.length > 1) - { - getUserPreferences(pathElements[0], pathElements[1], request, response); - } - else - { - getUserList(pathElements, request, response); - } - } - - private void getUserPreferences(String authenticationProviderName, String userId, HttpServletRequest request, HttpServletResponse response) - throws IOException - { - Map preferences = null; - PreferencesProvider preferencesProvider = getPreferencesProvider(authenticationProviderName); - if (preferencesProvider == null) - { - response.sendError(HttpServletResponse.SC_NOT_FOUND, "Preferences provider is not configured"); - return; - } - try - { - preferences = preferencesProvider.getPreferences(userId); - - sendJsonResponse(preferences, request, response); - } - catch (SecurityException e) - { - response.sendError(HttpServletResponse.SC_FORBIDDEN, "Viewing of preferences is not allowed"); - return; - } - } - - private void getUserList(String[] pathElements, HttpServletRequest request, HttpServletResponse response) throws IOException - { - List> users = null; - try - { - users = getUsers(pathElements); - } - catch (Exception e) - { - LOGGER.debug("Bad preferences request", e); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); - } - sendJsonResponse(users, request, response); - } - - private PreferencesProvider getPreferencesProvider(String authenticationProviderName) - { - AuthenticationProvider authenticationProvider = getAuthenticationProvider(authenticationProviderName); - if (authenticationProvider == null) - { - throw new IllegalArgumentException(String.format("Authentication provider '%s' is not found", - authenticationProviderName)); - } - PreferencesProvider preferencesProvider = authenticationProvider.getPreferencesProvider(); - return preferencesProvider; - } - - private AuthenticationProvider getAuthenticationProvider(String authenticationProviderName) - { - Broker broker = getBroker(); - Collection authenticationProviders = broker.getAuthenticationProviders(); - for (AuthenticationProvider authenticationProvider : authenticationProviders) - { - if (authenticationProviderName.equals(authenticationProvider.getName())) - { - return authenticationProvider; - } - } - return null; - } - - private List> getUsers(String[] pathElements) - { - List> users = new ArrayList>(); - String authenticationProviderName = pathElements != null && pathElements.length > 0 ? pathElements[0] : null; - - Broker broker = getBroker(); - Collection authenticationProviders = broker.getAuthenticationProviders(); - for (AuthenticationProvider authenticationProvider : authenticationProviders) - { - if (authenticationProviderName != null && !authenticationProvider.getName().equals(authenticationProviderName)) - { - continue; - } - PreferencesProvider preferencesProvider = authenticationProvider.getPreferencesProvider(); - if (preferencesProvider != null) - { - Set usernames = preferencesProvider.listUserIDs(); - for (String name : usernames) - { - Map userMap = new HashMap(); - userMap.put(User.NAME, name); - userMap.put("authenticationProvider", authenticationProvider.getName()); - users.add(userMap); - } - } - } - return users; - } - - /* - * removes preferences - */ - @Override - protected void doDeleteWithSubjectAndActor(HttpServletRequest request, HttpServletResponse response) throws IOException - { - Broker broker = getBroker(); - Collection authenticationProviders = broker.getAuthenticationProviders(); - Map> providerUsers = new HashMap>(); - Map requestProviders = new HashMap(); - for (String path : request.getParameterValues("user")) - { - String[] elements = path.split("/"); - if (elements.length != 2) - { - throw new IllegalArgumentException("Illegal user parameter " + path); - } - - String userId = elements[1]; - - String providerName = elements[0]; - Set users = providerUsers.get(providerName); - - if (users == null) - { - AuthenticationProvider provider = findAuthenticationProviderByName(providerName, authenticationProviders); - if (provider == null) - { - throw new IllegalArgumentException("Cannot find provider with name '" + providerName + "'"); - } - users = new HashSet(); - providerUsers.put(providerName, users); - requestProviders.put(providerName, provider); - } - users.add(userId); - } - - if (!providerUsers.isEmpty()) - { - for (Map.Entry> entry : providerUsers.entrySet()) - { - String providerName = entry.getKey(); - AuthenticationProvider provider = requestProviders.get(providerName); - Set usersToDelete = entry.getValue(); - PreferencesProvider preferencesProvider = provider.getPreferencesProvider(); - - if (preferencesProvider != null && !usersToDelete.isEmpty()) - { - String[] users = usersToDelete.toArray(new String[usersToDelete.size()]); - try - { - preferencesProvider.deletePreferences(users); - } - catch (SecurityException e) - { - response.sendError(HttpServletResponse.SC_FORBIDDEN, "Deletion of preferences is not allowed"); - return; - } - } - } - } - - } - - protected AuthenticationProvider findAuthenticationProviderByName(String providerName, Collection authenticationProviders) - { - AuthenticationProvider provider = null; - for (AuthenticationProvider authenticationProvider : authenticationProviders) - { - if(authenticationProvider.getName().equals(providerName)) - { - provider = authenticationProvider; - break; - } - } - return provider; - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/AbstractSpecialisedAttributeLister.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/AbstractSpecialisedAttributeLister.java deleted file mode 100644 index c697603c6c..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/AbstractSpecialisedAttributeLister.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.management.plugin.servlet.rest.action; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.TreeMap; -import java.util.TreeSet; - -import org.apache.qpid.server.management.plugin.servlet.rest.Action; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.ConfiguredObjectAttribute; -import org.apache.qpid.server.model.ConfiguredObjectTypeRegistry; - -abstract class AbstractSpecialisedAttributeLister implements Action -{ - - - private static final String ATTRIBUTES = "attributes"; - private static final String DESCRIPTIONS = "descriptions"; - - @Override - final public Object perform(Map request, Broker broker) - { - ConfiguredObjectTypeRegistry typeRegistry = broker.getModel().getTypeRegistry(); - Collection> groupProviderTypes = - typeRegistry.getTypeSpecialisations(getCategoryClass()); - - Map attributes = new TreeMap(); - - for (Class groupProviderType : groupProviderTypes) - { - Collection> typeSpecificAttributes = - typeRegistry.getTypeSpecificAttributes(groupProviderType); - - Map data = new HashMap(); - - Collection attributeNames = new TreeSet<>(); - Map descriptions = new HashMap<>(); - for(ConfiguredObjectAttribute attr : typeSpecificAttributes) - { - attributeNames.add(attr.getName()); - if(!"".equals(attr.getDescription())) - { - descriptions.put(attr.getName(), attr.getDescription()); - } - } - data.put(ATTRIBUTES, attributeNames); - data.put(DESCRIPTIONS, descriptions); - - attributes.put(ConfiguredObjectTypeRegistry.getType(groupProviderType), data); - } - return attributes; - } - - abstract Class getCategoryClass(); - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListAccessControlProviderAttributes.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListAccessControlProviderAttributes.java deleted file mode 100644 index 1eb3f9a9ac..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListAccessControlProviderAttributes.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.management.plugin.servlet.rest.action; - -import org.apache.qpid.server.model.AccessControlProvider; - -public class ListAccessControlProviderAttributes extends AbstractSpecialisedAttributeLister -{ - @Override - public String getName() - { - return ListAccessControlProviderAttributes.class.getSimpleName(); - } - - @Override - Class getCategoryClass() - { - return AccessControlProvider.class; - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListBrokerAttribute.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListBrokerAttribute.java deleted file mode 100644 index dc414e6a64..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListBrokerAttribute.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.management.plugin.servlet.rest.action; - -import java.util.Map; - -import org.apache.qpid.server.management.plugin.servlet.rest.Action; -import org.apache.qpid.server.model.Broker; - -public class ListBrokerAttribute implements Action -{ - - private final String _attributeName; - private final String _name; - - public ListBrokerAttribute(String attributeName, String name) - { - _attributeName = attributeName; - _name = name; - } - - @Override - public String getName() - { - return _name; - } - - @Override - public Object perform(Map request, Broker broker) - { - return broker.getAttribute(_attributeName); - } - -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListGroupProviderAttributes.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListGroupProviderAttributes.java deleted file mode 100644 index ecb4320f1f..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListGroupProviderAttributes.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.management.plugin.servlet.rest.action; - -import org.apache.qpid.server.model.GroupProvider; - -public class ListGroupProviderAttributes extends AbstractSpecialisedAttributeLister -{ - @Override - public String getName() - { - return ListGroupProviderAttributes.class.getSimpleName(); - } - - @Override - Class getCategoryClass() - { - return GroupProvider.class; - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListTimeZones.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListTimeZones.java deleted file mode 100644 index 56bc7b1bf7..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/servlet/rest/action/ListTimeZones.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.server.management.plugin.servlet.rest.action; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.TimeZone; - -import org.apache.qpid.server.management.plugin.servlet.rest.Action; -import org.apache.qpid.server.model.Broker; - -public class ListTimeZones implements Action -{ - - private static final String[] TIMEZONE_REGIONS = { "Africa", "America", "Antarctica", "Arctic", "Asia", "Atlantic", "Australia", - "Europe", "Indian", "Pacific" }; - - @Override - public String getName() - { - return ListTimeZones.class.getSimpleName(); - } - - @Override - public Object perform(Map request, Broker broker) - { - List timeZoneDetails = new ArrayList(); - String[] ids = TimeZone.getAvailableIDs(); - long currentTime = System.currentTimeMillis(); - Date currentDate = new Date(currentTime); - for (String id : ids) - { - int cityPos = id.indexOf("/"); - if (cityPos > 0 && cityPos < id.length() - 1) - { - String region = id.substring(0, cityPos); - for (int i = 0; i < TIMEZONE_REGIONS.length; i++) - { - if (region.equals(TIMEZONE_REGIONS[i])) - { - TimeZone tz = TimeZone.getTimeZone(id); - int offset = tz.getOffset(currentTime)/60000; - String city = id.substring(cityPos + 1).replace('_', ' '); - timeZoneDetails.add(new TimeZoneDetails(id, tz.getDisplayName(tz.inDaylightTime(currentDate), TimeZone.SHORT), offset, city, region)); - break; - } - } - } - } - return timeZoneDetails; - } - - public static class TimeZoneDetails - { - private String id; - private String name; - private int offset; - private String city; - private String region; - - public TimeZoneDetails(String id, String name, int offset, String city, String region) - { - super(); - this.id = id; - this.name = name; - this.offset = offset; - this.city = city; - this.region = region; - } - - public String getId() - { - return id; - } - - public String getName() - { - return name; - } - - public int getOffset() - { - return offset; - } - - public String getCity() - { - return city; - } - - public String getRegion() - { - return region; - } - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/session/LoginLogoutReporter.java b/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/session/LoginLogoutReporter.java deleted file mode 100644 index 7e0d13fddb..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/session/LoginLogoutReporter.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.management.plugin.session; - -import java.security.Principal; -import java.security.PrivilegedAction; - -import javax.security.auth.Subject; -import javax.servlet.http.HttpSession; -import javax.servlet.http.HttpSessionBindingEvent; -import javax.servlet.http.HttpSessionBindingListener; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.EventLoggerProvider; -import org.apache.qpid.server.logging.messages.ManagementConsoleMessages; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; - -/** - * Logs {@link ManagementConsoleMessages#OPEN(String)} and {@link ManagementConsoleMessages#CLOSE(String)} - * messages. A single instance of this class must be placed in the {@link HttpSession} immediately after - * the user has successfully logged-in, and removed (or the whole session invalidated) as the user logs out. - */ -public class LoginLogoutReporter implements HttpSessionBindingListener -{ - private static final Logger LOGGER = LoggerFactory.getLogger(LoginLogoutReporter.class); - private final Subject _subject; - private final Principal _principal; - private final EventLoggerProvider _eventLoggerProvider; - - public LoginLogoutReporter(Subject subject, EventLoggerProvider eventLoggerProvider) - { - super(); - _subject = subject; - _principal = AuthenticatedPrincipal.getAuthenticatedPrincipalFromSubject(_subject); - _eventLoggerProvider = eventLoggerProvider; - } - - @Override - public void valueBound(HttpSessionBindingEvent arg0) - { - reportLogin(); - } - - @Override - public void valueUnbound(HttpSessionBindingEvent arg0) - { - reportLogout(); - } - - private void reportLogin() - { - if (LOGGER.isDebugEnabled()) - { - LOGGER.debug("User logging in : " + _principal); - } - - Subject.doAs(_subject, new PrivilegedAction() - { - @Override - public Void run() - { - getEventLogger().message(ManagementConsoleMessages.OPEN(_principal.getName())); - return null; - } - }); - } - - private void reportLogout() - { - if (LOGGER.isDebugEnabled()) - { - LOGGER.debug("User logging out : " + _principal); - } - - Subject.doAs(_subject, new PrivilegedAction() - { - @Override - public Void run() - { - getEventLogger().message(ManagementConsoleMessages.CLOSE(_principal.getName())); - return null; - } - }); - } - - public EventLogger getEventLogger() - { - return _eventLoggerProvider.getEventLogger(); - } -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/accesscontrolprovider/aclfile/add.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/accesscontrolprovider/aclfile/add.html deleted file mode 100644 index 796988c410..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/accesscontrolprovider/aclfile/add.html +++ /dev/null @@ -1,64 +0,0 @@ - - -

- -
-
Server path or upload*:
-
- - - - -
- -
-
-
- - -
- -
- - -
-
- -
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/accesscontrolprovider/showAclFile.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/accesscontrolprovider/showAclFile.html deleted file mode 100644 index 24cef75737..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/accesscontrolprovider/showAclFile.html +++ /dev/null @@ -1,27 +0,0 @@ - -
-
-
Path:
-
-
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/addAccessControlProvider.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/addAccessControlProvider.html deleted file mode 100644 index 64f8078314..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/addAccessControlProvider.html +++ /dev/null @@ -1,66 +0,0 @@ - -
-
-
-
-
-
-
Name*:
-
- -
-
-
-
Type*:
-
- -
-
- -
-
-
-
-
-
-
-
- -
- - -
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/addAuthenticationProvider.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/addAuthenticationProvider.html deleted file mode 100644 index 5a565e72e3..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/addAuthenticationProvider.html +++ /dev/null @@ -1,64 +0,0 @@ - -
-
-
-
-
-
- Authentication Provider -
-
Name*:
-
- -
-
-
-
Type*:
-
- -
-
-
-
-
-
-
- -
-
-
- - -
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/addBinding.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/addBinding.html deleted file mode 100644 index d4ac5877cb..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/addBinding.html +++ /dev/null @@ -1,64 +0,0 @@ - -
-
-
- -
-
Exchange Name*:
-
-
-
-
-
-
Queue Name*:
-
-
-
-
-
-
Binding Key*:
-
- -
-
- -
-
- Binding Arguments -
NOTE: Only arguments with name and value will be submitted. To edit, please, click on a grid cell.
-
-
- - -
-
-
- -
- -
-
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/addExchange.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/addExchange.html deleted file mode 100644 index 25e9752392..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/addExchange.html +++ /dev/null @@ -1,74 +0,0 @@ - -
-
-
-
-
Name*:
-
- -
-
-
-
Exchange Type:
-
- -
-
-
-
Durable?
-
- -
-
- - -
- -
- -
-
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/addGroupProvider.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/addGroupProvider.html deleted file mode 100644 index b622fe94d2..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/addGroupProvider.html +++ /dev/null @@ -1,66 +0,0 @@ - - -
-
-
-
-
-
-
Name*:
-
- -
-
-
-
Type*:
-
- -
-
-
-
-
-
-
-
-
-
- -
- - -
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/addPort.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/addPort.html deleted file mode 100644 index 10b79987a5..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/addPort.html +++ /dev/null @@ -1,260 +0,0 @@ - -
-
-
- -
- -
-
- -
-
- -
-
- -
-
- -
-
- -
-
- -
-
- -
-
- -
-
-
- -
-
-
- -
-
- -
-
-
- -
-
- -
-
-
- -
-
- -
-
-
- -
-
-
- -
-
- -
-
-
- -
-
-
- -
-
- -
-
-
-
-
- -
-
-
- -
-
- -
-
-
- -
-
-
- -
-
- -
-
-
- -
-
-
-
- -
-
- -
-
-
-
- -
-
- -
-
-
- -
-
- Trust Stores: -
-
- -
-
- - - - - - - -
NamePeers Only
-
-
-
- - -
-
- - -
-
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/addPreferencesProvider.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/addPreferencesProvider.html deleted file mode 100644 index e3984e1ae2..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/addPreferencesProvider.html +++ /dev/null @@ -1,28 +0,0 @@ - -
-
- -
- -
- - - -
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/addQueue.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/addQueue.html deleted file mode 100644 index 61f0de22d8..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/addQueue.html +++ /dev/null @@ -1,344 +0,0 @@ - -
-
-
- -
-
Queue Name*:
-
- -
-
-
-
Queue Type:
-
- -
-
-
- - - - - - - -
-
Durable?
-
- -
-
-
-
Persist Messages?
-
- -
-
-
-
Maximum Ttl:
-
- -
-
-
-
Minimum Ttl:
-
- -
-
- -
-
- Flow Control Settings -
-
Capacity:
-
- -
-
-
-
Resume Capacity:
-
- -
-
-
-
-
- -
-
- Alerting Settings -
-
Queue Depth:
-
- -
-
-
-
Queue Depth:
-
- -
-
-
-
Message Age:
-
- -
-
-
-
Message Size:
-
- -
-
-
-
Gap between alerts:
-
- -
-
-
-
-
- -
-
- Other Settings -
-
Maximum Delivery Retries:
-
- -
-
-
-
Create DLQ?
-
- -
-
- -
-
Configuring maximum delivery retries on a queue which has no DLQ or alternate
exchange will result in messages being discarded after the limit is reached.
- -
-
Message Group Key:
-
- -
-
-
-
Shared Message Groups?
-
- -
-
-
-
-
- -
-
-
- -
- - -
- -
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/addStore.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/addStore.html deleted file mode 100644 index a1903d456e..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/addStore.html +++ /dev/null @@ -1,66 +0,0 @@ - - -
-
-
-
-
-
-
Name*:
-
- -
-
-
-
Type*:
-
- -
-
-
-
-
-
-
-
-
-
- -
- - -
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/addVirtualHostNodeAndVirtualHost.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/addVirtualHostNodeAndVirtualHost.html deleted file mode 100644 index a2ee2c1b4b..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/addVirtualHostNodeAndVirtualHost.html +++ /dev/null @@ -1,136 +0,0 @@ - -
-
-
- - -
-
-
- Virtual Host Node -
-
Name*:
-
- -
-
-
-
Type*:
-
- -
-
-
- -
- -
-
- -
-
- -
-
-
- -
-
- - - -
-
-
- -
- -
-
-
- - -
-
-
- - -
-
-
- Virtual Host -
-
Type*:
-
- -
-
-
- -
- -
-
-
- -
-
-
-
-
- - -
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/addUser.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/addUser.html deleted file mode 100644 index 785605f694..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/addUser.html +++ /dev/null @@ -1,42 +0,0 @@ - -
-
-
- - - - - - - - - -
User Name*:
Password*
-
- - - - -
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/external/add.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/external/add.html deleted file mode 100644 index 11a9bf8ea0..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/external/add.html +++ /dev/null @@ -1,30 +0,0 @@ - -
-
Use full DN:
-
- -
-
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/external/show.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/external/show.html deleted file mode 100644 index ac065c723c..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/external/show.html +++ /dev/null @@ -1,26 +0,0 @@ - -
-
-
Use full DN:
-
-
-
-
- diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/filebased/add.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/filebased/add.html deleted file mode 100644 index 53eb786722..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/filebased/add.html +++ /dev/null @@ -1,31 +0,0 @@ - -
-
Path*:
-
- -
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/filebased/show.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/filebased/show.html deleted file mode 100644 index 5060656964..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/filebased/show.html +++ /dev/null @@ -1,26 +0,0 @@ - -
-
-
Path to file:
-
-
-
-
- diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/setPassword.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/setPassword.html deleted file mode 100644 index 3d67463abd..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/setPassword.html +++ /dev/null @@ -1,42 +0,0 @@ - -
-
-
- - - - - - - - - -
User Name:
Password*
-
- - - - -
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/showPrincipalDatabaseAuthenticationManager.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/showPrincipalDatabaseAuthenticationManager.html deleted file mode 100644 index e6c067fddf..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/showPrincipalDatabaseAuthenticationManager.html +++ /dev/null @@ -1,27 +0,0 @@ - -
-
-
- - -
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/simpleldap/add.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/simpleldap/add.html deleted file mode 100644 index 3a3b613564..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/simpleldap/add.html +++ /dev/null @@ -1,133 +0,0 @@ - -
-
-
LDAP server URL*:
-
- -
-
-
-
LDAP authentication URL
-
- -
-
-
-
Trust Store:
-
- -
-
-
-
Search context*:
-
- -
-
-
-
Search filter*:
-
- -
-
-
-
Search username:
-
- -
-
-
-
Search password:
-
- -
-
-
-
Authenticate without search:
-
- -
-
-
-
-
-
LDAP Context Factory:
-
- -
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/simpleldap/show.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/simpleldap/show.html deleted file mode 100644 index e2f1da32af..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/authenticationprovider/simpleldap/show.html +++ /dev/null @@ -1,58 +0,0 @@ - -
-
-
LDAP server URL:
-
-
-
-
Search context:
-
-
-
-
Search filter:
-
-
-
-
Search user name:
-
-
-
-
Search password:
-
-
-
-
Trust Store:
-
-
-
-
Bind without search:
-
-
-
-
LDAP Context Factory:
-
-
-
-
LDAP authentication URL:
-
-
-
-
- diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/common/ContextVariablesEditor.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/common/ContextVariablesEditor.html deleted file mode 100644 index 60fc0843eb..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/common/ContextVariablesEditor.html +++ /dev/null @@ -1,35 +0,0 @@ - -
-
-
-
-
- - - - - - -
-
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/common/ResourceWidget.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/common/ResourceWidget.html deleted file mode 100644 index e47fa6ca6d..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/common/ResourceWidget.html +++ /dev/null @@ -1,48 +0,0 @@ - - - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/common/TimeZoneSelector.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/common/TimeZoneSelector.html deleted file mode 100644 index 2b2fca7d8a..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/common/TimeZoneSelector.html +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - - - - - -
Use UTC time: - -
Time Zone: - - - - - - - -
RegionCity
-
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/css/apidocs.css b/qpid/java/broker-plugins/management-http/src/main/java/resources/css/apidocs.css deleted file mode 100644 index 5baecf7c02..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/css/apidocs.css +++ /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. - * - */ -html, body { - margin-top: 20px; - margin-left: 40px; - margin-right: 40px; - padding: 0; - font-family: Lucida Sans,Lucida Grande,Arial,sans-serif !important; - font-size: 13px !important; - background: white; - color: #333; -} - -th, td { - text-align: left; -} - -.type { - font-family: "Courier New", courier, monospace; -} - -table.types td.name { - width: 20em; -} - -table.attributes td.name { - font-family: "Courier New", courier, monospace; - width: 20em; -} - -table.attributes td.type { - width: 7em; -} - -table.api td,th { - vertical-align: top; -} - - -table.api td.type { - width: 12em; -} - - -table.api td.path { - width: 20em; -} - - -table.api td.description { - width: 25em; -} - -table.api a:link { - color: #333; - text-decoration: none; -} - -table.api a:visited { - color: #666; - text-decoration: none; -} - - -div.restriction { - border-bottom: 1px dotted #666; - display: inline; -} diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/css/common.css b/qpid/java/broker-plugins/management-http/src/main/java/resources/css/common.css deleted file mode 100644 index ec31709987..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/css/common.css +++ /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. - * - */ -* { - outline: none !important; -} - -html, body { - height: 100%; - margin: 0; - margin-right: 40px; - padding: 0; - overflow: hidden; - font-family: Lucida Sans,Lucida Grande,Arial !important; - font-size: 13px !important; - background: white; - color: #333; -} - -.clear { - clear: both; -} - -.hidden { - display: none; -} - -#pageLayout { - height: 100%; -} -button { - -webkit-transition: background-color 0.2s linear; - border-radius:4px; - -moz-border-radius: 4px 4px 4px 4px; - -moz-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15); - background-color: #E4F2FF; - background-position: center top; - background-repeat: repeat-x; - border: 1px solid #769DC0; - padding: 2px 8px 4px; - font-size:1em; -} - -button:hover { - background-color: #AFD9FF; - color: #000000; -} - -h1 { - font-size:1.5em; -} - -.header { - height:100px; - background:url("../images/qpid-logo.png") left center no-repeat -} - -.logo { - text-align:left; - vertical-align: top; - font-weight:600; - height: 90px; - padding-left: 200px; - padding-top: 1px; - padding-bottom: 10px; - font-size:14px; - font-family:"Verdana", cursive; -} - -.footer { - color:#000000; - clear:both; - text-align:center; - font-size:11px; - line-height:17px; - -} - -div .messages { - width: 100%; - height: 350px; -} - -.formBox { - margin: 10px 5px; -} - -.formBox legend { - font-weight: bold; - margin-left: 5px; - background-color: white; -} - -.formBox fieldset { - padding: 5px; - border: .1em solid lightgrey; - border-radius: 5px; -} - -.formLabel-labelCell, .tableContainer-labelCell { - width: 300px; - font-weight: bold; -} - -.tableContainer-labelCell { - float: none; -} - -.formLabel-labelCell { - margin-left: 5px; - float: left; - } - -.formValue-valueCell { - float: left; -} - -.formBox .addPermittedNodeList { - width: 15em; -} - -.formBox .addPermittedNodeList select { - width: 100%; -} - -.formLabel-controlCell { - padding: 1px; - float: left; -} - -.columnDefDialogButtonIcon { - background: url("../dojo/dojox/grid/enhanced/resources/images/sprite_icons.png") no-repeat; - background-position: -260px 2px; - width: 14px; - height: 14px; -} - -.logViewerIcon { - background: url("../images/log-viewer.png") no-repeat; - width: 14px; - height: 16px; -} - -.downloadLogsIcon { - background: url("../images/download.png") no-repeat; - width: 14px; - height: 14px; -} - -.dojoxGridFBarClearFilterButtontnIcon -{ - background: url("../dojo/dojox/grid/enhanced/resources/images/sprite_icons.png") no-repeat; - background-position: -120px -18px; - width: 14px; - height: 14px; -} - -.rowNumberLimitIcon -{ - background: url("../dojo/dojox/grid/enhanced/resources/images/sprite_icons.png") no-repeat; - background-position: -240px -18px; - width: 14px; - height: 14px; -} - -.gridRefreshIcon -{ - background: url("../images/refresh.png") no-repeat; - width: 16px; - height: 16px; -} - -.gridAutoRefreshIcon -{ - background: url("../images/auto-refresh.png") no-repeat; - width: 16px; - height: 16px; -} - -.redBackground tr{ background-color:#ffdcd7 !important; background-image: none !important;} -.yellowBackground tr{background-color:#fbfddf !important; background-image: none !important;} -.grayBackground tr{background-color:#eeeeee !important; background-image: none !important;} -.dojoxGridRowOdd.grayBackground tr{ background-color:#e9e9e9 !important; background-image: none !important;} -.dojoxGridRowOdd.yellowBackground tr{background-color:#fafdd5 !important; background-image: none !important;} -.dojoxGridRowOdd.redBackground tr{background-color:#f4c1c1 !important; background-image: none !important;} - -.preferencesIcon -{ - background: url("../images/gear.png") no-repeat; - width: 16px; - height: 16px; -} - -.helpIcon -{ - background: url("../images/help.png") no-repeat; - width: 16px; - height: 16px; -} - -.loadingIcon -{ - background: url("../dojo/dojox/image/resources/images/loading.gif") no-repeat; - width: 16px; - height: 16px; - background-size: contain; - display: inline-block; -} - -.loadedIcon -{ - background: url("../dojo/dijit/icons/images/commonIconsObjActEnabled_rtl.png") no-repeat; - background-position: -352px -0px; - width: 16px; - height: 16px; - display: inline-block; -} - -.fileUpload -{ - float: right; - padding: 5px; -} - -.infoMessage -{ - padding: 5px; - font-style: italic; -} - -.alignLeft { - float: left; - display: inline-block; -} - -.alignRight { - float: right; - display: inline-block; -} - -.multiLineValue { - display: inline-block; -} - -.haOptionLabel { - font-weight: bold; - margin-left: 5px; -} - -.editNoteBanner { - font-style: italic; - margin: 0px 0px 10px 5px; -} - -#errorDialog { - overflow: auto; - width: 400px; -} - -.errorDialogErrorPrimary { - font-weight: bold; - margin-bottom: 10px; - max-width: 350px; -} - -.errorDialogErrorSecondary { - font-style: italic; -} - -/* Required to keep queue type radio buttons on one line when dialog adds scrollbar */ -#addQueue { - overflow: auto; - width: 630px; -} - -#authenticatedUserControls { - max-width: 300px; -} - -.claro .dojoxCheckedMultiSelectWrapper { - height: auto; -} - -.claro .dojoxCheckedMultiSelect .dojoxCheckedMultiSelectWrapper { - border: none; - background-color: transparent; -} - -.dijitMultiSelect { - width : 14.75em; -} - -.highlightedText -{ - font-weight: bold; -} - -.normalText -{ - font-weight: normal; -} - -.contextEditor -{ - margin-left:5px; - margin-right:5px; -} - -.contextGrid -{ - width:100%; - max-height: 140px; - overflow: auto; -} - -.qpidDialogPaneActionBar -{ - margin-left:-10px; - margin-right:-10px; - margin-bottom:-10px; - margin-top:5px; -} \ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/editBroker.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/editBroker.html deleted file mode 100644 index 993a2c7505..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/editBroker.html +++ /dev/null @@ -1,119 +0,0 @@ - -
-
-
-
-
-
-
Name*:
-
- -
-
-
-
Default Virtual Host*:
-
- -
-
-
-
Statistics reporting period (ms):
-
- -
-
-
-
Statistics reporting period enabled:
-
- -
-
- -
-
- Global Connection Defaults -
-
Maximum number of sessions:
-
- -
-
-
-
Heart beat delay (ms)::
-
- -
-
-
-
- -
-
-
- -
-
-
- - -
-
-
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/editQueue.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/editQueue.html deleted file mode 100644 index e7b33ed6f9..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/editQueue.html +++ /dev/null @@ -1,300 +0,0 @@ - -
-
-
-
-
-
NOTE: All changes will only take effect after Virtual Host restart.
-
-
Queue Name:
-
- -
-
- -
-
Queue Type:
-
- -
-
-
- - - - - - - -
-
Durable?
-
- -
-
-
-
Persist Messages?
-
- -
-
-
-
Maximum Ttl:
-
- -
-
-
-
Minimum Ttl:
-
- -
-
- -
- -
-
- Flow Control Settings -
-
Capacity:
-
- -
-
-
-
Resume Capacity:
-
- -
-
-
-
-
- -
-
- Alerting Settings -
-
Queue Depth:
-
- -
-
-
-
Queue Depth:
-
- -
-
-
-
Message Age:
-
- -
-
-
-
Message Size:
-
- -
-
-
-
Gap between alerts:
-
- -
-
-
-
-
- -
-
- Other Settings -
-
Maximum Delivery Retries:
-
- -
-
-
-
-
- -
-
-
-
-
- - -
-
- -
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/editVirtualHost.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/editVirtualHost.html deleted file mode 100644 index 8e03dfdd17..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/editVirtualHost.html +++ /dev/null @@ -1,137 +0,0 @@ - -
-
-
-
-
-
NOTE: All changes will only take effect after Virtual Host restart.
-
-
Name*:
-
- -
-
- -
- -
-
- Store transaction settings -
-
Idle Timeout Warn:
-
- -
-
-
-
Idle Timeout Close:
-
- -
-
-
-
Open Timeout Warn:
-
- -
-
-
-
Open Timeout Close:
-
- -
-
-
-
- -
-
- House keeping settings -
-
Check period (ms):
-
- -
-
-
-
Thread count:
-
- -
-
-
-
-
- -
-
Dead letter queue enabled:
-
- - -
-
- -
- -
-
-
-
-
- - -
-
-
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/editVirtualHostNode.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/editVirtualHostNode.html deleted file mode 100644 index 59597845a2..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/editVirtualHostNode.html +++ /dev/null @@ -1,56 +0,0 @@ - -
-
-
-
-
-
NOTE: All changes will only take effect after Virtual Host Node restart.
-
-
Name*:
-
- -
-
- -
- -
- -
-
-
-
-
- -
- - -
-
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/footer.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/footer.html deleted file mode 100644 index 44fa4fda36..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/footer.html +++ /dev/null @@ -1,28 +0,0 @@ - - - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/grid/showColumnDefDialog.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/grid/showColumnDefDialog.html deleted file mode 100644 index 535b9a1fe5..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/grid/showColumnDefDialog.html +++ /dev/null @@ -1,32 +0,0 @@ - -
-
-
Select columns to display:
-
-
-
- - -
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/grid/showRowNumberLimitDialog.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/grid/showRowNumberLimitDialog.html deleted file mode 100644 index cacdf49e66..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/grid/showRowNumberLimitDialog.html +++ /dev/null @@ -1,33 +0,0 @@ - -
-
-
Set the maximum number of rows to cache and display:
- -
-
- - -
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/group/addGroupMember.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/group/addGroupMember.html deleted file mode 100644 index e479e8cb74..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/group/addGroupMember.html +++ /dev/null @@ -1,38 +0,0 @@ - -
-
-
- - - - - -
Name*:
-
- -
- -
-
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/group/showGroup.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/group/showGroup.html deleted file mode 100644 index c84e794ac1..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/group/showGroup.html +++ /dev/null @@ -1,32 +0,0 @@ - -
- Name: -
-
-
-
- - -
-
-
- diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/addGroup.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/addGroup.html deleted file mode 100644 index 29ce2ebe6c..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/addGroup.html +++ /dev/null @@ -1,39 +0,0 @@ - -
-
-
- - - - - -
Group Name*:
-
- -
- -
- -
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/groupfile/add.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/groupfile/add.html deleted file mode 100644 index 7fc458cd4f..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/groupfile/add.html +++ /dev/null @@ -1,37 +0,0 @@ - -
-
-
Path*:
-
- -
-
- -
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/groupfile/show.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/groupfile/show.html deleted file mode 100644 index 740c65fd38..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/groupfile/show.html +++ /dev/null @@ -1,25 +0,0 @@ - -
-
-
Path to file:
-
-
-
-
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/showGroupManagingGroupProvider.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/showGroupManagingGroupProvider.html deleted file mode 100644 index 62a6c7537c..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/groupprovider/showGroupManagingGroupProvider.html +++ /dev/null @@ -1,30 +0,0 @@ - -
-
-
-
- - -
-
- -
diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/auto-refresh.png b/qpid/java/broker-plugins/management-http/src/main/java/resources/images/auto-refresh.png deleted file mode 100644 index 493636f467..0000000000 Binary files a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/auto-refresh.png and /dev/null differ diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/download.png b/qpid/java/broker-plugins/management-http/src/main/java/resources/images/download.png deleted file mode 100644 index b64b41d476..0000000000 Binary files a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/download.png and /dev/null differ diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/gear.png b/qpid/java/broker-plugins/management-http/src/main/java/resources/images/gear.png deleted file mode 100644 index 0bb4394b46..0000000000 Binary files a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/gear.png and /dev/null differ diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/help.png b/qpid/java/broker-plugins/management-http/src/main/java/resources/images/help.png deleted file mode 100644 index f7d3698d25..0000000000 Binary files a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/help.png and /dev/null differ diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/log-viewer.png b/qpid/java/broker-plugins/management-http/src/main/java/resources/images/log-viewer.png deleted file mode 100644 index 858fd48beb..0000000000 Binary files a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/log-viewer.png and /dev/null differ diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/qpid-logo.png b/qpid/java/broker-plugins/management-http/src/main/java/resources/images/qpid-logo.png deleted file mode 100644 index ae0fbb462f..0000000000 Binary files a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/qpid-logo.png and /dev/null differ diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/refresh.png b/qpid/java/broker-plugins/management-http/src/main/java/resources/images/refresh.png deleted file mode 100644 index 083044979b..0000000000 Binary files a/qpid/java/broker-plugins/management-http/src/main/java/resources/images/refresh.png and /dev/null differ diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/index.html b/qpid/java/broker-plugins/management-http/src/main/java/resources/index.html deleted file mode 100644 index 896640fd67..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/index.html +++ /dev/null @@ -1,137 +0,0 @@ - - - - - - Qpid Management - - - - - - - - - - - - - - - - -
-
- -
- -
-
-
-
-
-
-
-
-
-
- -
-
-
-
- 000 - error -
- -
-
- Please login again and retry your operation. -
-
- Please correct the problem and retry your operation. -
-
-
-
- - -
-
-
-
- - - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/README.txt b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/README.txt deleted file mode 100644 index 6ef692ce31..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/README.txt +++ /dev/null @@ -1,8 +0,0 @@ -Crypto-JS -========= - -Version: 3.1.2 - -These files are from Crypto-JS (https://code.google.com/p/crypto-js/) by Jeff Mott. - - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/enc-base64-min.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/enc-base64-min.js deleted file mode 100644 index 7ab054d94b..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/enc-base64-min.js +++ /dev/null @@ -1,8 +0,0 @@ -/* -CryptoJS v3.1.2 -code.google.com/p/crypto-js -(c) 2009-2013 by Jeff Mott. All rights reserved. -code.google.com/p/crypto-js/wiki/License -*/ -(function(){var h=CryptoJS,j=h.lib.WordArray;h.enc.Base64={stringify:function(b){var e=b.words,f=b.sigBytes,c=this._map;b.clamp();b=[];for(var a=0;a>>2]>>>24-8*(a%4)&255)<<16|(e[a+1>>>2]>>>24-8*((a+1)%4)&255)<<8|e[a+2>>>2]>>>24-8*((a+2)%4)&255,g=0;4>g&&a+0.75*g>>6*(3-g)&63));if(e=c.charAt(64))for(;b.length%4;)b.push(e);return b.join("")},parse:function(b){var e=b.length,f=this._map,c=f.charAt(64);c&&(c=b.indexOf(c),-1!=c&&(e=c));for(var c=[],a=0,d=0;d< -e;d++)if(d%4){var g=f.indexOf(b.charAt(d-1))<<2*(d%4),h=f.indexOf(b.charAt(d))>>>6-2*(d%4);c[a>>>2]|=(g|h)<<24-8*(a%4);a++}return j.create(c,a)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})(); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/hmac-sha1.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/hmac-sha1.js deleted file mode 100644 index 0d50d81a1e..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/crypto-js/hmac-sha1.js +++ /dev/null @@ -1,17 +0,0 @@ -/* -CryptoJS v3.1.2 -code.google.com/p/crypto-js -(c) 2009-2013 by Jeff Mott. All rights reserved. -code.google.com/p/crypto-js/wiki/License -*/ -var CryptoJS=CryptoJS||function(g,l){var e={},d=e.lib={},m=function(){},k=d.Base={extend:function(a){m.prototype=this;var c=new m;a&&c.mixIn(a);c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}, -p=d.WordArray=k.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=l?c:4*a.length},toString:function(a){return(a||n).stringify(this)},concat:function(a){var c=this.words,q=a.words,f=this.sigBytes;a=a.sigBytes;this.clamp();if(f%4)for(var b=0;b>>2]|=(q[b>>>2]>>>24-8*(b%4)&255)<<24-8*((f+b)%4);else if(65535>>2]=q[b>>>2];else c.push.apply(c,q);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<< -32-8*(c%4);a.length=g.ceil(c/4)},clone:function(){var a=k.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],b=0;b>>2]>>>24-8*(f%4)&255;b.push((d>>>4).toString(16));b.push((d&15).toString(16))}return b.join("")},parse:function(a){for(var c=a.length,b=[],f=0;f>>3]|=parseInt(a.substr(f, -2),16)<<24-4*(f%8);return new p.init(b,c/2)}},j=b.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var b=[],f=0;f>>2]>>>24-8*(f%4)&255));return b.join("")},parse:function(a){for(var c=a.length,b=[],f=0;f>>2]|=(a.charCodeAt(f)&255)<<24-8*(f%4);return new p.init(b,c)}},h=b.Utf8={stringify:function(a){try{return decodeURIComponent(escape(j.stringify(a)))}catch(c){throw Error("Malformed UTF-8 data");}},parse:function(a){return j.parse(unescape(encodeURIComponent(a)))}}, -r=d.BufferedBlockAlgorithm=k.extend({reset:function(){this._data=new p.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=h.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,b=c.words,f=c.sigBytes,d=this.blockSize,e=f/(4*d),e=a?g.ceil(e):g.max((e|0)-this._minBufferSize,0);a=e*d;f=g.min(4*a,f);if(a){for(var k=0;ka;a++){if(16>a)m[a]=d[e+a]|0;else{var c=m[a-3]^m[a-8]^m[a-14]^m[a-16];m[a]=c<<1|c>>>31}c=(n<<5|n>>>27)+l+m[a];c=20>a?c+((j&h|~j&g)+1518500249):40>a?c+((j^h^g)+1859775393):60>a?c+((j&h|j&g|h&g)-1894007588):c+((j^h^ -g)-899497514);l=g;g=h;h=j<<30|j>>>2;j=n;n=c}b[0]=b[0]+n|0;b[1]=b[1]+j|0;b[2]=b[2]+h|0;b[3]=b[3]+g|0;b[4]=b[4]+l|0},_doFinalize:function(){var d=this._data,e=d.words,b=8*this._nDataBytes,g=8*d.sigBytes;e[g>>>5]|=128<<24-g%32;e[(g+64>>>9<<4)+14]=Math.floor(b/4294967296);e[(g+64>>>9<<4)+15]=b;d.sigBytes=4*e.length;this._process();return this._hash},clone:function(){var e=d.clone.call(this);e._hash=this._hash.clone();return e}});g.SHA1=d._createHelper(l);g.HmacSHA1=d._createHmacHelper(l)})(); -(function(){var g=CryptoJS,l=g.enc.Utf8;g.algo.HMAC=g.lib.Base.extend({init:function(e,d){e=this._hasher=new e.init;"string"==typeof d&&(d=l.parse(d));var g=e.blockSize,k=4*g;d.sigBytes>k&&(d=e.finalize(d));d.clamp();for(var p=this._oKey=d.clone(),b=this._iKey=d.clone(),n=p.words,j=b.words,h=0;h>>2]|=(d[e>>>2]>>>24-8*(e%4)&255)<<24-8*((b+e)%4);else if(65535>>2]=d[e>>>2];else c.push.apply(c,d);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<< -32-8*(c%4);a.length=h.ceil(c/4)},clone:function(){var a=m.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],d=0;d>>2]>>>24-8*(b%4)&255;d.push((e>>>4).toString(16));d.push((e&15).toString(16))}return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b>>3]|=parseInt(a.substr(b, -2),16)<<24-4*(b%8);return new r.init(d,c/2)}},n=l.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var d=[],b=0;b>>2]>>>24-8*(b%4)&255));return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b>>2]|=(a.charCodeAt(b)&255)<<24-8*(b%4);return new r.init(d,c)}},j=l.Utf8={stringify:function(a){try{return decodeURIComponent(escape(n.stringify(a)))}catch(c){throw Error("Malformed UTF-8 data");}},parse:function(a){return n.parse(unescape(encodeURIComponent(a)))}}, -u=g.BufferedBlockAlgorithm=m.extend({reset:function(){this._data=new r.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=j.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,d=c.words,b=c.sigBytes,e=this.blockSize,f=b/(4*e),f=a?h.ceil(f):h.max((f|0)-this._minBufferSize,0);a=f*e;b=h.min(4*a,b);if(a){for(var g=0;gn;){var j;a:{j=k;for(var u=h.sqrt(j),t=2;t<=u;t++)if(!(j%t)){j=!1;break a}j=!0}j&&(8>n&&(m[n]=l(h.pow(k,0.5))),r[n]=l(h.pow(k,1/3)),n++);k++}var a=[],f=f.SHA256=q.extend({_doReset:function(){this._hash=new g.init(m.slice(0))},_doProcessBlock:function(c,d){for(var b=this._hash.words,e=b[0],f=b[1],g=b[2],j=b[3],h=b[4],m=b[5],n=b[6],q=b[7],p=0;64>p;p++){if(16>p)a[p]= -c[d+p]|0;else{var k=a[p-15],l=a[p-2];a[p]=((k<<25|k>>>7)^(k<<14|k>>>18)^k>>>3)+a[p-7]+((l<<15|l>>>17)^(l<<13|l>>>19)^l>>>10)+a[p-16]}k=q+((h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25))+(h&m^~h&n)+r[p]+a[p];l=((e<<30|e>>>2)^(e<<19|e>>>13)^(e<<10|e>>>22))+(e&f^e&g^f&g);q=n;n=m;m=h;h=j+k|0;j=g;g=f;f=e;e=k+l|0}b[0]=b[0]+e|0;b[1]=b[1]+f|0;b[2]=b[2]+g|0;b[3]=b[3]+j|0;b[4]=b[4]+h|0;b[5]=b[5]+m|0;b[6]=b[6]+n|0;b[7]=b[7]+q|0},_doFinalize:function(){var a=this._data,d=a.words,b=8*this._nDataBytes,e=8*a.sigBytes; -d[e>>>5]|=128<<24-e%32;d[(e+64>>>9<<4)+14]=h.floor(b/4294967296);d[(e+64>>>9<<4)+15]=b;a.sigBytes=4*d.length;this._process();return this._hash},clone:function(){var a=q.clone.call(this);a._hash=this._hash.clone();return a}});s.SHA256=q._createHelper(f);s.HmacSHA256=q._createHmacHelper(f)})(Math); -(function(){var h=CryptoJS,s=h.enc.Utf8;h.algo.HMAC=h.lib.Base.extend({init:function(f,g){f=this._hasher=new f.init;"string"==typeof g&&(g=s.parse(g));var h=f.blockSize,m=4*h;g.sigBytes>m&&(g=f.finalize(g));g.clamp();for(var r=this._oKey=g.clone(),l=this._iKey=g.clone(),k=r.words,n=l.words,j=0;j>5] |= (challengeBytes[i/8] & 0xFF)<<(i%32); - } - var challengeStr = digestsBase.wordToString(wa).substring(0,challengeBytes.length); - - var digest = user + " " + MD5._hmac(challengeStr, password, digestsBase.outputTypes.Hex); - var id = data.id; - - var response = base64.encode(encodeUTF8( digest )); - - dojo.xhrPost({ - // The URL of the request - url: saslServiceUrl, - content: { - id: id, - response: response - }, - handleAs: "json", - failOk: true - }).then(callbackFunction, errorHandler); - - }, - function(error) - { - if(error.status == 403) - { - alert("Authentication Failed"); - } - else - { - alert(error); - } - }); - - - -}; - - var saslScramSha1 = function saslScramSha1(user, password, saslMechanism, callbackFunction) { - saslScram("sha1",user,password,saslMechanism,callbackFunction); - }; - - var saslScramSha256 = function saslScramSha1(user, password, saslMechanism, callbackFunction) { - saslScram("sha256",user,password,saslMechanism,callbackFunction); - }; - - var saslScram = function saslScramSha1(mechanism, user, password, saslMechanism, callbackFunction) { - - var DIGEST = mechanism.toUpperCase(); - var HMAC = "Hmac"+DIGEST; - - script.get("js/crypto-js/hmac-"+mechanism+".js").then( function() - { - script.get("js/crypto-js/enc-base64-min.js").then ( function() - { - - var toBase64 = function toBase64( input ) - { - var result = []; - for(var i = 0; i < input.length; i++) - { - result[i] = input.charCodeAt(i); - } - return base64.encode( result ) - }; - - var fromBase64 = function fromBase64( input ) - { - var decoded = base64.decode( input ); - var result = ""; - for(var i = 0; i < decoded.length; i++) - { - result+= String.fromCharCode(decoded[i]); - } - return result; - }; - - var xor = function xor(lhs, rhs) { - var words = []; - for(var i = 0; i < lhs.words.length; i++) - { - words.push(lhs.words[i]^rhs.words[i]); - } - return CryptoJS.lib.WordArray.create(words); - }; - - var hasNonAscii = function hasNonAscii(name) { - for(var i = 0; i < name.length; i++) { - if(name.charCodeAt(i) > 127) { - return true; - } - } - return false; - }; - - var generateSaltedPassword = function generateSaltedPassword(salt, password, iterationCount) - { - var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo[DIGEST], password); - - hmac.update(salt); - hmac.update(CryptoJS.enc.Hex.parse("00000001")); - - var result = hmac.finalize(); - var previous = null; - for(var i = 1 ;i < iterationCount; i++) - { - hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo[DIGEST], password); - hmac.update( previous != null ? previous : result ); - previous = hmac.finalize(); - result = xor(result, previous); - } - return result; - - }; - - GS2_HEADER = "n,,"; - - if(!hasNonAscii(user)) { - - user = user.replace(/=/g, "=3D"); - user = user.replace(/,/g, "=2C"); - - clientNonce = uuid(); - clientFirstMessageBare = "n=" + user + ",r=" + clientNonce; - dojo.xhrPost({ - // The URL of the request - url: saslServiceUrl, - content: { - mechanism: saslMechanism, - response: toBase64(GS2_HEADER + clientFirstMessageBare) - }, - handleAs: "json", - failOk: true - }).then(function (data) { - var serverFirstMessage = fromBase64(data.challenge); - var id = data.id; - - var parts = serverFirstMessage.split(","); - nonce = parts[0].substring(2); - if (!nonce.substr(0, clientNonce.length) == clientNonce) { - alert("Authentication error - server nonce does not start with client nonce") - } - else { - var salt = CryptoJS.enc.Base64.parse(parts[1].substring(2)); - var iterationCount = parts[2].substring(2); - var saltedPassword = generateSaltedPassword(salt, password, iterationCount) - var clientFinalMessageWithoutProof = "c=" + toBase64(GS2_HEADER) + ",r=" + nonce; - var authMessage = clientFirstMessageBare + "," + serverFirstMessage + "," + clientFinalMessageWithoutProof; - var clientKey = CryptoJS[HMAC]("Client Key", saltedPassword); - var storedKey = CryptoJS[DIGEST](clientKey); - var clientSignature = CryptoJS[HMAC](authMessage, storedKey); - var clientProof = xor(clientKey, clientSignature); - var serverKey = CryptoJS[HMAC]("Server Key", saltedPassword); - serverSignature = CryptoJS[HMAC](authMessage, serverKey); - dojo.xhrPost({ - // The URL of the request - url: saslServiceUrl, - content: { - id: id, - response: toBase64(clientFinalMessageWithoutProof - + ",p=" + clientProof.toString(CryptoJS.enc.Base64)) - }, - handleAs: "json", - failOk: true - }).then(function (data) { - var serverFinalMessage = fromBase64(data.challenge); - if (serverSignature.toString(CryptoJS.enc.Base64) == serverFinalMessage.substring(2)) { - callbackFunction(); - } - else { - errorHandler("Server signature did not match"); - } - - - }, errorHandler); - } - - }, errorHandler); - } - else - { - alert("Username '"+name+"' is invalid"); - } - - }, errorHandler); - }, errorHandler); - }; - -var containsMechanism = function containsMechanism(mechanisms, mech) -{ - for (var i = 0; i < mechanisms.length; i++) { - if (mechanisms[i] == mech) { - return true; - } - } - - return false; -}; - -var SaslClient = {}; - -SaslClient.authenticate = function(username, password, callbackFunction) -{ - dojo.xhrGet({ - url: saslServiceUrl, - handleAs: "json", - failOk: true - }).then(function(data) - { - var mechMap = data.mechanisms; - if(containsMechanism(mechMap, "SCRAM-SHA-256")) - { - saslScramSha256(username, password, "SCRAM-SHA-256", callbackFunction) - } - else if(containsMechanism(mechMap, "SCRAM-SHA-1")) - { - saslScramSha1(username, password, "SCRAM-SHA-1", callbackFunction) - } - else if (containsMechanism(mechMap, "CRAM-MD5")) - { - saslCramMD5(username, password, "CRAM-MD5", callbackFunction); - } - else if (containsMechanism(mechMap, "CRAM-MD5-HEX")) - { - var hashedPassword = MD5(password, digestsBase.outputTypes.Hex); - saslCramMD5(username, hashedPassword, "CRAM-MD5-HEX", callbackFunction); - } - else if (containsMechanism(mechMap, "PLAIN")) - { - saslPlain(username, password, callbackFunction); - } - else - { - alert("No supported SASL mechanism offered: " + mechMap); - } - }, errorHandler); -}; - -SaslClient.getUser = function(callbackFunction) -{ - dojo.xhrGet({ - url: saslServiceUrl, - handleAs: "json", - failOk: true - }).then(callbackFunction, errorHandler); -}; - -return SaslClient; -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/ConsoleHelper.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/ConsoleHelper.js deleted file mode 100644 index 9cebf48ce6..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/ConsoleHelper.js +++ /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. - * - */ -define(["dojo/_base/xhr", "dojo/domReady!"], function (xhr) { - - var preferencesDialog = null; - var helpURL = null; - - return { - showPreferencesDialog: function () { - if (preferencesDialog == null) - { - require(["qpid/management/Preferences", "dojo/ready"], function(PreferencesDialog, ready){ - ready(function(){ - preferencesDialog = new PreferencesDialog(); - preferencesDialog.showDialog(); - }); - }); - } - else - { - preferencesDialog.showDialog(); - } - }, - getHelpUrl: function() - { - if (!helpURL) - { - xhr.get({ - sync: true, - url: "api/latest/broker", - content: { "depth" : 1, "includeSysContext" : true }, - handleAs: "json" - }).then(function(data) { - var broker = data[0]; - if ("context" in broker && "qpid.helpURL" in broker["context"] ) - { - helpURL = broker["context"]["qpid.helpURL"]; - } - else - { - helpURL = "http://qpid.apache.org/"; - } - }); - } - return helpURL; - }, - showHelp: function() - { - var newWindow = window.open(this.getHelpUrl(),'QpidHelp','height=600,width=600,scrollbars=1,location=1,resizable=1,status=0,toolbar=0,titlebar=1,menubar=0', true); - newWindow.focus(); - } - }; - -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/ContextVariablesEditor.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/ContextVariablesEditor.js deleted file mode 100644 index a3e4023273..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/ContextVariablesEditor.js +++ /dev/null @@ -1,558 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define([ - "qpid/common/util", - "dojo/_base/xhr", - "dojo/_base/declare", - "dojo/_base/array", - "dojo/_base/connect", - "dojo/_base/lang", - "dojo/dom-construct", - "dojo/parser", - "dojo/query", - "dojo/store/Memory", - "dojo/data/ObjectStore", - "dijit/_WidgetBase", - "dijit/registry", - "dojo/text!common/ContextVariablesEditor.html", - "dijit/form/Button", - "dojox/grid/EnhancedGrid", - "dojox/grid/enhanced/_Plugin", - "dijit/form/Select", - "dojox/validate/us", - "dojox/validate/web", - "dojo/domReady!"], -function (util, xhr, declare, array, connect, lang, domConstruct, parser, query, Memory, ObjectStore, _WidgetBase, registry, template) - { - - return declare("qpid.common.ContextVariablesEditor", [_WidgetBase], { - - value: null, - effectiveValues: null, - inheritedActualValues: null, - domNode: null, - _grid: null, - _addButton: null, - _deleteButton: null, - _filterBox: null, - _nextGridItemId: 0, - _dynamicInheritedContext: {}, - - constructor: function(args) - { - this._args = args; - }, - - buildRendering: function() - { - this.domNode = domConstruct.create("div", {innerHTML: template}); - parser.parse(this.domNode); - }, - - postCreate: function() - { - this.inherited(arguments); - var that = this; - var gridNode = query(".grid", this.domNode)[0]; - var addButtonNode = query(".addButton", this.domNode)[0]; - var deleteButtonNode = query(".deleteButton", this.domNode)[0]; - var addButton = registry.byNode(addButtonNode); - var deleteButton = registry.byNode(deleteButtonNode); - var layout = [[ - { name: "Name", field: "name", width: "40%", editable: true}, - { name: 'Actual Value', field: 'actualValue', width: '30%', editable: true}, - { name: 'Effective Value', field: 'effectiveValue', width: '30%', editable: false} - ]]; - var data = []; - var objectStore = new dojo.data.ObjectStore({objectStore: new Memory({data:data, idProperty: "id"})}); - var grid = new dojox.grid.EnhancedGrid({ - selectionMode: "multiple", - store: objectStore, - singleClickEdit: true, - structure: layout, - autoHeight: true, - sortFields: [{attribute: 'name', descending: false}], - plugins: {indirectSelection: true} - }, gridNode); - grid.canEdit = function(inCell, inRowIndex) - { - var item = grid.getItem(inRowIndex); - return inCell.field == "actualValue" || (inCell.field=="name" && item && item["inherited"] == false); - }; - - this._grid = grid; - this._deleteButton = deleteButton; - this._addButtonNode = addButtonNode; - - var toggleGridButtons = function(index) - { - var data = grid.selection.getSelected(); - deleteButton.set("disabled", !data || data.length==0); - }; - - connect.connect(grid.selection, 'onSelected', toggleGridButtons); - connect.connect(grid.selection, 'onDeselected', toggleGridButtons); - connect.connect(grid, 'onStyleRow' , this, function(row) { that._onStyleRow(row); }); - - deleteButton.set("disabled", true); - addButton.on("click", function(event) { that._newItem(); }); - deleteButton.on("click", function(event) { that._deleteSelected(); }); - grid.on("applyEdit", function(inRowIndex) { that._onEdit(inRowIndex); }); - grid.startup(); - this._filterBox = registry.byNode(query(".filter", this.domNode)[0]); - this._filterBox.on("change", function(value) { if (value) { that._filter(value); } }); - }, - resize: function() - { - this._grid.render(); - }, - load: function(restUrl, data) - { - data = data || {}; - var actualValues = data.actualValues; - var allEffectiveValues = data.effectiveValues; - var inheritedActualValues = data.inheritedActualValues; - if (!actualValues) - { - xhr.get( - { - url: restUrl, - sync: true, - content: { actuals: true }, - handleAs: "json", - load: function(data) - { - actualValues = data[0].context; - } - } - ); - } - if (!allEffectiveValues) - { - xhr.get( - { - url: restUrl, - sync: true, - content: { actuals: false }, - handleAs: "json", - load: function(data) - { - allEffectiveValues = data[0].context; - } - } - ); - } - if (!inheritedActualValues) - { - xhr.get( - { - url: restUrl, - sync: true, - content: { actuals: true, inheritedActuals: true}, - handleAs: "json", - load: function(data) - { - inheritedActualValues = data[0].context; - } - } - ); - } - this.setData(actualValues, allEffectiveValues, inheritedActualValues); - }, - loadInheritedData: function(restUrl) - { - var allEffectiveValues = null; - xhr.get( - { - url: restUrl, - sync: true, - content: { actuals: false }, - handleAs: "json", - load: function(data) - { - allEffectiveValues = data[0].context; - } - } - ); - - var inheritedActualValues = null; - xhr.get( - { - url: restUrl, - sync: true, - content: { actuals: true, inheritedActuals: true}, - handleAs: "json", - load: function(data) - { - inheritedActualValues = data[0].context; - } - } - ); - - this.setData({}, allEffectiveValues, inheritedActualValues); - }, - setData: function(actualValues, allEffectiveValues, inheritedActualValues) - { - this.value = actualValues; - this.effectiveValues = allEffectiveValues; - this.inheritedActualValues = inheritedActualValues; - - var values = this._mergeValues(actualValues, allEffectiveValues, inheritedActualValues); - this._originalValues = values; - - var grid = this._grid; - if (grid) - { - // delete previous store data - grid.store.fetch({ - onComplete:function(items,request) - { - if(items.length) - { - array.forEach(items, function(item) - { - grid.store.deleteItem(item); - }); - } - } - }); - - // add new data into grid store - this._nextGridItemId = 0; - for(var i=0; i 0) - { - array.forEach(data, function(selectedItem) { - if (selectedItem !== null && !selectedItem["inherited"]) - { - grid.store.deleteItem(selectedItem); - that._deleteOriginalItem(selectedItem.name); - } - }); - grid.store.save(); - grid.selection.deselectAll(); - this._valueChanged(); - } - }, - _deleteOriginalItem: function(key) - { - for(var i=0;i< this._originalValues.length;i++) - { - if (this._originalValues[i].name == key) - { - this._originalValues = this._originalValues.splice(i, 1); - break; - } - } - }, - _onEdit:function(inRowIndex) - { - var grid = this._grid; - var item = grid.getItem(inRowIndex); - var previousItems = this._originalValues; - var previousItemActualValue = null; - for(var i=0;i 0) - { - array.forEach(items, function(item) - { - if (item !== null && item.name && ((item["inherited"] && item.changed) || !item["inherited"])) - { - value[item.name]=item.actualValue; - } - }); - } - } - }); - if (!util.equals(this.value, value)) - { - this.value = value; - this._handleOnChange(value); - } - } - }, - _setValueAttr: function(actualValues) - { - this.value = actualValues; - if (this.inheritedActualValues!=null && this.effectiveValues != null) - { - this.setData(this.value, this.effectiveValues, this.inheritedActualValues); - } - }, - _setEffectiveValuesAttr: function(effectiveValues) - { - this.effectiveValues = effectiveValues; - if (this.value != null && this.inheritedActualValues !=null) - { - this.setData(this.value, this.effectiveValues, this.inheritedActualValues); - } - }, - _setInheritedActualValues: function(inheritedActualValues) - { - this.inheritedActualValues = inheritedActualValues; - if (this.value!= null && this.effectiveValues != null) - { - this.setData(this.value, this.effectiveValues, this.inheritedActualValues); - } - }, - _mergeValues: function(actualValues, allEffectiveValues, inheritedActualValues) - { - var fields = []; - - if (allEffectiveValues) - { - for(var key in allEffectiveValues) - { - if (!actualValues || !(key in actualValues)) - { - var actualValue = inheritedActualValues && key in inheritedActualValues ? inheritedActualValues[key] : allEffectiveValues[key]; - fields.push({name: key, actualValue: actualValue, effectiveValue: allEffectiveValues[key], "inherited": true}); - } - } - } - - if (actualValues) - { - for(var key in actualValues) - { - var effectiveValue = allEffectiveValues && key in allEffectiveValues ? allEffectiveValues[key]: actualValues[key]; - fields.push({name: key, actualValue: actualValues[key], effectiveValue: effectiveValue, "inherited": false}); - } - } - return fields; - }, - _handleOnChange: function(newValue) - { - if (!util.equals(this._lastValueReported, newValue)) - { - this._lastValueReported = newValue; - if(this._onChangeHandle) - { - this._onChangeHandle.remove(); - } - this._onChangeHandle = this.defer(function() - { - this._onChangeHandle = null; - this.onChange(newValue); - }); - } - } - - }); -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/FormWidgetMixin.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/FormWidgetMixin.js deleted file mode 100644 index 11160e9608..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/FormWidgetMixin.js +++ /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. - * - */ -define(["dojo/_base/declare"], function(declare) -{ - return declare("qpid.common.FormWidgetMixin", null, - { - name: "", - value: "", - _onChangeActive: false, - - compare: function(val1, val2) - { - if(typeof val1 == "number" && typeof val2 == "number") - { - return (isNaN(val1) && isNaN(val2)) ? 0 : val1 - val2; - } - else if(val1 > val2) - { - return 1; - } - else if(val1 < val2) - { - return -1; - } - else - { - return 0; - } - }, - onChange: function() - { - }, - _setValueAttr: function(newValue, priorityChange) - { - this._handleOnChange(newValue, priorityChange); - }, - _handleOnChange: function(newValue, priorityChange) - { - this._set("value", newValue); - if(this._lastValueReported == undefined && (priorityChange === null || !this._onChangeActive)) - { - this._resetValue = this._lastValueReported = newValue; - } - this._pendingOnChange = this._pendingOnChange || (typeof newValue != typeof this._lastValueReported) - || (this.compare(newValue, this._lastValueReported) != 0); - if(( priorityChange || priorityChange === undefined) && this._pendingOnChange) - { - this._lastValueReported = newValue; - this._pendingOnChange = false; - if(this._onChangeActive) - { - if(this._onChangeHandle) - { - this._onChangeHandle.remove(); - } - this._onChangeHandle = this.defer(function() { this._onChangeHandle = null; this.onChange(newValue); }); - } - } - }, - create: function() - { - this.inherited(arguments); - this._onChangeActive = true; - }, - destroy: function() - { - if(this._onChangeHandle) - { - this._onChangeHandle.remove(); - this.onChange(this._lastValueReported); - } - this.inherited(arguments); - }, - undo: function() - { - this._setValueAttr(this._lastValueReported, false); - }, - reset: function() - { - this._hasBeenBlurred = false; - this._setValueAttr(this._resetValue, true); - } - }); -}); \ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/ResourceWidget.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/ResourceWidget.js deleted file mode 100644 index bee38149da..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/ResourceWidget.js +++ /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. - * - */ -define([ - "dojo/_base/declare", - "dojo/_base/array", - "dojo/_base/lang", - "qpid/common/util", - "dijit/_Widget", - "dijit/_TemplatedMixin", - "dijit/_WidgetsInTemplateMixin", - "qpid/common/FormWidgetMixin", - "dojo/text!common/ResourceWidget.html", - "dojox/html/entities", - "dojox/form/Uploader", - "dijit/form/Button", - "dijit/form/ValidationTextBox", - "dojox/validate/us", - "dojox/validate/web", - "dojo/domReady!"], -function (declare, array, lang, util, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, FormWidgetMixin, template, entities) -{ - - return declare("qpid.common.ResourceWidget", [_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, FormWidgetMixin], - { - templateString: template, - fileReaderSupported: window.FileReader ? true : false, - displayWarningWhenFileReaderUnsupported: false, - isDebug: false, - uploaded: false, - - buildRendering: function() - { - //Strip out the apache comment header from the template html as comments unsupported. - this.templateString = this.templateString.replace(//g, ""); - this.inherited(arguments); - }, - postCreate: function() - { - this.inherited(arguments); - - if(this._resetValue === undefined) - { - this._lastValueReported = this._resetValue = this.value; - } - - var that = this; - - if (this.fileReaderSupported) - { - this.fileReader= new FileReader(); - this.fileReader.onload = function(evt) {that._uploadFileComplete(evt);}; - this.fileReader.onerror = function(ex) {console.error("Failed to load file for " + this.name, ex);}; - this.uploader.on("change", function(selected){that._fileChanged(selected)}); - this.clearButton.on("click", function(event){that._fileClearButtonClicked(event)}); - } - else - { - // Fall back for IE8/9 which do not support FileReader - this.uploadFields.style.display = "none"; - if (this.displayWarningWhenFileReaderUnsupported) - { - this.unsupportedWarning.className = this.unsupportedWarning.className.replace("hidden", ""); - } - } - this.resourceLocation.on("blur", function(){that._pathChanged()}); - this._originalValue = arguments.value; - if (this.placeHolder) - { - this.resourceLocation.set("placeHolder", this.placeHolder); - } - if (this.promptMessage) - { - this.resourceLocation.set("promptMessage", this.promptMessage); - } - if (this.title) - { - this.resourceLocation.set("title", this.title); - } - this.resourceLocation.set("required", this.required ? true : false); - this.uploadData.style.display = "none"; - }, - startup: function() - { - if (this.fileReaderSupported) - { - this.uploader.startup(); - } - }, - _fileChanged: function (evt) - { - var file = this.uploader.domNode.children[0].files[0]; - this.selectedFileName = file.name; - this.selectedFile.innerHTML = file.name; - this.selectedFileStatus.className = "loadingIcon"; - if (this.isDebug) - { - this._log("Beginning to read file " + file.name + " for " + this.name); - } - this.fileReader.readAsDataURL(file); - }, - _uploadFileComplete: function(evt) - { - var reader = evt.target; - var result = reader.result; - if (this.isDebug) - { - this._log(this.name + " file read complete, contents " + result); - } - this.set("value", result); - }, - _fileClearButtonClicked: function(event) - { - this.uploaded = false; - this.uploader.reset(); - this.set("value", this._resetValue); - }, - _pathChanged: function() - { - var serverPathValue = this.resourceLocation.get("value") || this._resetValue; - this.set("value", serverPathValue); - if (this.uploaded ) - { - this.uploaded = !serverPathValue; - } - }, - _setValueAttr: function(newValue, priorityChange) - { - var isDataUrl = this.uploaded || ( newValue && newValue.indexOf("data:") == 0 ); - if (isDataUrl) - { - this._initUploaded(true); - } - else - { - this.resourceLocation.set("value", newValue); - this.selectedFileName = null; - this.selectedFileStatus.className = ""; - this.selectedFile.innerHTML = ""; - this.resourceLocation.set("required", this.required ? true : false); - this.resourceLocation.setDisabled(false); - this.clearButton.setDisabled(true); - this.uploadData.style.display = "none"; - } - this.inherited(arguments); - }, - _log: function(message) - { - if (this.isDebug) - { - console.log(message); - } - }, - _setPlaceHolderAttr: function(newValue) - { - this.resourceLocation.set("placeHolder", newValue); - }, - _setUploadedAttr: function(uploaded) - { - this.uploaded = uploaded; - this._initUploaded(uploaded); - }, - _initUploaded: function(uploaded) - { - if (uploaded) - { - this.uploadData.style.display = "block"; - this.selectedFileStatus.className = "loadedIcon"; - this.selectedFile.innerHTML = this.selectedFileName || "uploaded data"; - this.resourceLocation.set("value", ""); - this.resourceLocation.setDisabled(true); - this.resourceLocation.set("required", false); - this.clearButton.setDisabled(false); - this.selectedFileStatus.className = "loadedIcon"; - } - } - } - ); -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/TimeZoneSelector.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/TimeZoneSelector.js deleted file mode 100644 index fa4bd8c873..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/TimeZoneSelector.js +++ /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. - * - */ -define([ - "dojo/_base/declare", - "dojo/_base/array", - "dojo/dom-construct", - "dojo/parser", - "dojo/query", - "dojo/dom-style", - "dojo/store/Memory", - "dijit/_WidgetBase", - "dijit/registry", - "dojo/text!common/TimeZoneSelector.html", - "qpid/common/timezone", - "dijit/form/ComboBox", - "dijit/form/FilteringSelect", - "dijit/form/CheckBox", - "dojox/validate/us", - "dojox/validate/web", - "dojo/domReady!"], -function (declare, array, domConstruct, parser, query, domStyle, Memory, _WidgetBase, registry, template, timezone) { - - var preferencesRegions = ["Africa","America","Antarctica","Arctic","Asia","Atlantic","Australia","Europe","Indian","Pacific"]; - - function initSupportedRegions() - { - var supportedRegions = [{"id": "undefined", "name": "Undefined"}]; - for(var j = 0; j 1) - { - this._regionSelector.timeZone = value; - this._regionSelector.set("value", elements[0]); - this._citySelector.set("value", value); - } - else - { - this._regionSelector.set("value", "undefined"); - } - } - } - else - { - this._utcSelector.set("checked", false); - this._regionSelector.set("value", "undefined"); - } - this.value = value; - this._handleOnChange(value); - }, - - destroy: function() - { - if (this.domNode) - { - this.domNode.destroy(); - this.domNode = null; - } - _regionSelector: null; - _citySelector: null; - _utcSelector: null; - }, - - onChange: function(newValue){}, - - _handleOnChange: function(newValue) - { - if (this._lastValueReported != newValue) - { - this._lastValueReported = newValue; - if(this._onChangeHandle) - { - this._onChangeHandle.remove(); - } - this._onChangeHandle = this.defer(function() - { - this._onChangeHandle = null; - this.onChange(newValue); - }); - } - } - - }); -}); \ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/UpdatableStore.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/UpdatableStore.js deleted file mode 100644 index 64d557c242..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/UpdatableStore.js +++ /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. - * - */ -define(["dojo/json", - "qpid/common/util", - "dojo/store/Memory", - "dojox/grid/DataGrid", - "dojo/data/ObjectStore", - "dojo/store/Observable"], function (json, util, Memory, DataGrid, ObjectStore, Observable) { - - function UpdatableStore( data, divName, structure, func, props, Grid, notObservable ) { - - var that = this; - var GridType = DataGrid; - - that.memoryStore = new Memory({data: data, idProperty: "id"}); - that.store = notObservable ? that.memoryStore : new Observable(that.memoryStore); - that.dataStore = ObjectStore({objectStore: that.store}); - - var gridProperties = { store: that.dataStore, - structure: structure, - autoHeight: true - }; - if(props) { - for(var prop in props) { - if(props.hasOwnProperty(prop)) - { - gridProperties[ prop ] = props[ prop ]; - } - } - } - - if(Grid) - { - GridType = Grid; - } - - that.grid = new GridType(gridProperties, divName); - - // since we created this grid programmatically, call startup to render it - that.grid.startup(); - - if( func ) - { - func(that); - } - - } - - UpdatableStore.prototype.update = function(data) - { - var changed = false; - var store = this.store; - var theItem; - - // handle deletes - // iterate over existing store... if not in new data then remove - store.query({ }).forEach(function(object) { - if(data) { - for(var i=0; i < data.length; i++) { - if(data[i].id == object.id) { - return; - } - } - } - store.remove(object.id); - changed = true; - }); - - // iterate over data... - if(data) { - for(var i=0; i < data.length; i++) - { - if(theItem = store.get(data[i].id)) - { - var modified = !util.equals(theItem, data[i]); - if(modified) - { - if (store.notify) - { - // Seems that we are required to update the item that the store already holds - for(var propName in data[i]) - { - if(data[i].hasOwnProperty(propName)) - { - if(theItem[ propName ] != data[i][ propName ]) - { - theItem[ propName ] = data[i][ propName ]; - } - } - } - // and tell it we have done so - store.notify(theItem, data[i].id); - } - else - { - store.put(data[i], {overwrite: true}); - } - changed = true; - } - } else { - // if not in the store then add - store.put(data[i]); - changed = true; - } - } - } - - return changed; - }; - - function removeItemsFromArray(items, numberToRemove) - { - if (items) - { - if (numberToRemove > 0 && items.length > 0) - { - if (numberToRemove >= items.length) - { - numberToRemove = numberToRemove - items.length; - items.length = 0 - } - else - { - items.splice(0, numberToRemove); - numberToRemove = 0; - } - } - } - return numberToRemove; - }; - - UpdatableStore.prototype.append = function(data, limit) - { - var changed = false; - var items = this.memoryStore.data; - - if (limit) - { - var totalSize = items.length + (data ? data.length : 0); - var numberToRemove = totalSize - limit; - - if (numberToRemove > 0) - { - changed = true; - numberToRemove = removeItemsFromArray(items, numberToRemove); - if (numberToRemove > 0) - { - removeItemsFromArray(data, numberToRemove); - } - } - } - - if (data && data.length > 0) - { - changed = true; - items.push.apply(items, data); - } - - this.memoryStore.setData(items); - return changed; - }; - - UpdatableStore.prototype.close = function() - { - this.dataStore.close(); - this.dataStore = null; - this.store = null; - this.memoryStore = null; - }; - return UpdatableStore; -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/footer.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/footer.js deleted file mode 100644 index ea13b1fc53..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/footer.js +++ /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. - * - */ -define(["dojo/_base/xhr", "dojo/query", "dojo/domReady!"], function (xhr, query) { - query('div[qpid-type="footer"]').forEach(function(node, index, arr) { - xhr.get({url: "footer.html", - sync: true, - load: function(data) { - node.innerHTML = data; - } }); - }); -}); - diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/formatter.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/formatter.js deleted file mode 100644 index 2f8683ee1c..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/formatter.js +++ /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. - * - */ - -define(function () { - return { - - formatBytes: function formatBytes(amount) - { - var returnVal = { units: "B", - value: "0"}; - - - if(amount < 1000) - { - returnVal.value = amount.toPrecision(3);; - } - else if(amount < 1000 * 1024) - { - returnVal.units = "KB"; - returnVal.value = (amount / 1024).toPrecision(3); - } - else if(amount < 1000 * 1024 * 1024) - { - returnVal.units = "MB"; - returnVal.value = (amount / (1024 * 1024)).toPrecision(3); - } - else if(amount < 1000 * 1024 * 1024 * 1024) - { - returnVal.units = "GB"; - returnVal.value = (amount / (1024 * 1024 * 1024)).toPrecision(3); - } - - return returnVal; - - }, - - formatTime: function formatTime(amount) - { - var returnVal = { units: "ms", - value: "0"}; - - if(amount < 1000) - { - returnVal.units = "ms"; - returnVal.value = amount.toString(); - } - else if(amount < 1000 * 60) - { - returnVal.units = "s"; - returnVal.value = (amount / 1000).toPrecision(3); - } - else if(amount < 1000 * 60 * 60) - { - returnVal.units = "min"; - returnVal.value = (amount / (1000 * 60)).toPrecision(3); - } - else if(amount < 1000 * 60 * 60 * 24) - { - returnVal.units = "hr"; - returnVal.value = (amount / (1000 * 60 * 60)).toPrecision(3); - } - else if(amount < 1000 * 60 * 60 * 24 * 7) - { - returnVal.units = "d"; - returnVal.value = (amount / (1000 * 60 * 60 * 24)).toPrecision(3); - } - else if(amount < 1000 * 60 * 60 * 24 * 365) - { - returnVal.units = "wk"; - returnVal.value = (amount / (1000 * 60 * 60 * 24 * 7)).toPrecision(3); - } - else - { - returnVal.units = "yr"; - returnVal.value = (amount / (1000 * 60 * 60 * 24 * 365)).toPrecision(3); - } - - return returnVal; - } - }; -}); \ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/ColumnDefDialog.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/ColumnDefDialog.js deleted file mode 100644 index a0b62082cb..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/ColumnDefDialog.js +++ /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. - * - */ - -define([ - "dojo/_base/declare", - "dojo/_base/event", - "dojo/_base/array", - "dojo/_base/lang", - "dojo/parser", - "dojo/dom-construct", - "dojo/query", - "dijit/registry", - "dijit/form/Button", - "dijit/form/CheckBox", - "dojox/grid/enhanced/plugins/Dialog", - "dojo/text!../../../grid/showColumnDefDialog.html", - "dojo/domReady!" -], function(declare, event, array, lang, parser, dom, query, registry, Button, CheckBox, Dialog, template ){ - - -return declare("qpid.common.grid.ColumnDefDialog", null, { - - grid: null, - containerNode: null, - _columns: [], - _dialog: null, - - constructor: function(args){ - var grid = this.grid = args.grid; - var that = this; - this.containerNode = dom.create("div", {innerHTML: template}); - parser.parse(this.containerNode).then(function(instances) - { - that._postParse(); - }); - }, - _postParse: function() - { - var submitButton = registry.byNode(query(".displayButton", this.containerNode)[0]); - this.closeButton = registry.byNode(query(".cancelButton", this.containerNode)[0]); - var columnsContainer = query(".columnList", this.containerNode)[0]; - - this._buildColumnWidgets(columnsContainer); - - this._dialog = new Dialog({ - "refNode": this.grid.domNode, - "title": "Grid Columns", - "content": this.containerNode - }); - - var self = this; - submitButton.on("click", function(e){self._onColumnsSelect(e); }); - this.closeButton.on("click", function(e){self._dialog.hide(); }); - - this._dialog.startup(); - }, - - destroy: function(){ - this._dialog.destroyRecursive(); - this._dialog = null; - this.grid = null; - this.containerNode = null; - this._columns = null; - }, - - showDialog: function(){ - this._initColumnWidgets(); - this._dialog.show(); - }, - - _initColumnWidgets: function() - { - var cells = this.grid.layout.cells; - for(var i in cells) - { - var cell = cells[i]; - this._columns[cell.name].checked = !cell.hidden; - } - }, - - _onColumnsSelect: function(evt){ - event.stop(evt); - var grid = this.grid; - grid.beginUpdate(); - var cells = grid.layout.cells; - try - { - for(var i in cells) - { - var cell = cells[i]; - var widget = this._columns[cell.name]; - grid.layout.setColumnVisibility(i, widget.checked); - } - } - finally - { - grid.endUpdate(); - this._dialog.hide(); - } - }, - - _buildColumnWidgets: function(columnsContainer) - { - var cells = this.grid.layout.cells; - for(var i in cells) - { - var cell = cells[i]; - var widget = new dijit.form.CheckBox({ - required: false, - checked: !cell.hidden, - label: cell.name, - name: this.grid.id + "_cchb_ " + i - }); - - this._columns[cell.name] = widget; - - var div = dom.create("div"); - div.appendChild(widget.domNode); - div.appendChild(dom.create("span", {innerHTML: cell.name})); - - columnsContainer.appendChild(div); - } - } - - }); - -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/EnhancedFilter.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/EnhancedFilter.js deleted file mode 100644 index 262210f879..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/EnhancedFilter.js +++ /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. - * - */ - -define([ - "dojo/_base/declare", - "dojo/_base/lang", - "dojo/_base/array", - "dijit/Toolbar", - "dojox/grid/enhanced/_Plugin", - "dojox/grid/enhanced/plugins/Dialog", - "dojox/grid/enhanced/plugins/filter/FilterLayer", - "dojox/grid/enhanced/plugins/filter/FilterDefDialog", - "dojox/grid/enhanced/plugins/filter/FilterStatusTip", - "dojox/grid/enhanced/plugins/filter/ClearFilterConfirm", - "dojox/grid/EnhancedGrid", - "dojo/i18n!dojox/grid/enhanced/nls/Filter", - "qpid/common/grid/EnhancedFilterTools" -], function(declare, lang, array, Toolbar, _Plugin, - Dialog, FilterLayer, FilterDefDialog, FilterStatusTip, ClearFilterConfirm, EnhancedGrid, nls, EnhancedFilterTools){ - - // override CriteriaBox#_getColumnOptions to show criteria for hidden columns with EnhancedFilter - dojo.extend(dojox.grid.enhanced.plugins.filter.CriteriaBox, { - _getColumnOptions: function(){ - var colIdx = this.dlg.curColIdx >= 0 ? String(this.dlg.curColIdx) : "anycolumn"; - var filterHidden = this.plugin.filterHidden; - return array.map(array.filter(this.plugin.grid.layout.cells, function(cell){ - return !(cell.filterable === false || (!filterHidden && cell.hidden)); - }), function(cell){ - return { - label: cell.name || cell.field, - value: String(cell.index), - selected: colIdx == String(cell.index) - }; - }); - } - }); - - // Enhanced filter has extra functionality for refreshing, limiting rows, displaying/hiding columns in the grid - var EnhancedFilter = declare("qpid.common.grid.EnhancedFilter", _Plugin, { - // summary: - // Accept the same plugin parameters as dojox.grid.enhanced.plugins.Filter and the following: - // - // filterHidden: boolean: - // Whether to display filtering criteria for hidden columns. Default to true. - // - // defaulGridRowLimit: int: - // Default limit for numbers of items to cache in the gris dtore - // - // disableFiltering: boolean: - // Whether to disable a filtering including filter button, clear filter button and filter summary. - // - // toolbar: dijit.Toolbar: - // An instance of toolbar to add the enhanced filter widgets. - - - // name: String - // plugin name - name: "enhancedFilter", - - // filterHidden: Boolean - // whether to filter hidden columns - filterHidden: true, - - constructor: function(grid, args){ - // summary: - // See constructor of dojox.grid.enhanced._Plugin. - this.grid = grid; - this.nls = nls; - - args = this.args = lang.isObject(args) ? args : {}; - if(typeof args.ruleCount != 'number' || args.ruleCount < 0){ - args.ruleCount = 0; - } - this.ruleCountToConfirmClearFilter = args.ruleCountToConfirmClearFilter || 5; - - if (args.filterHidden){ - this.filterHidden = args.filterHidden; - } - this.defaulGridRowLimit = args.defaulGridRowLimit; - this.disableFiltering = args.disableFiltering; - this.displayLastUpdateTime = args.displayLastUpdateTime; - - //Install UI components - var obj = { "plugin": this }; - - this.filterBar = ( args.toolbar && args.toolbar instanceof dijit.Toolbar) ? args.toolbar: new Toolbar(); - - if (!this.disableFiltering) - { - //Install filter layer - this._wrapStore(); - - this.clearFilterDialog = new Dialog({ - refNode: this.grid.domNode, - title: this.nls["clearFilterDialogTitle"], - content: new ClearFilterConfirm(obj) - }); - - this.filterDefDialog = new FilterDefDialog(obj); - this.filterDefDialog.filterDefPane._clearFilterBtn.set("label", "Clear Filter"); - - nls["statusTipTitleNoFilter"] = "Filter is not set"; - nls["statusTipMsg"] = "Click on 'Set Filter' button to specify filtering conditions"; - this.filterStatusTip = new FilterStatusTip(obj); - - var self = this; - var toggleClearFilterBtn = function (arg){ self.enhancedFilterTools.toggleClearFilterBtn(arg); }; - - this.filterBar.toggleClearFilterBtn = toggleClearFilterBtn; - - this.grid.isFilterBarShown = function (){return true}; - - this.connect(this.grid.layer("filter"), "onFilterDefined", function(filter){ - toggleClearFilterBtn(true); - }); - - //Expose the layer event to grid. - grid.onFilterDefined = function(){}; - this.connect(grid.layer("filter"), "onFilterDefined", function(filter){ - grid.onFilterDefined(grid.getFilter(), grid.getFilterRelation()); - }); - } - - // add extra buttons into toolbar - this.enhancedFilterTools = new EnhancedFilterTools({ - grid: grid, - toolbar: this.filterBar, - filterStatusTip: this.filterStatusTip, - clearFilterDialog: this.clearFilterDialog, - filterDefDialog: this.filterDefDialog, - defaulGridRowLimit: this.defaulGridRowLimit, - disableFiltering: this.disableFiltering, - displayLastUpdateTime: this.displayLastUpdateTime, - nls: nls, - ruleCountToConfirmClearFilter: this.ruleCountToConfirmClearFilter - }); - - this.filterBar.placeAt(this.grid.viewsHeaderNode, "before"); - this.filterBar.startup(); - - }, - - destroy: function(){ - this.inherited(arguments); - try - { - if (this.filterDefDialog) - { - this.filterDefDialog.destroy(); - this.filterDefDialog = null; - } - if (this.grid) - { - this.grid.unwrap("filter"); - this.grid = null; - } - if (this.filterBar) - { - this.filterBar.destroyRecursive(); - this.filterBar = null; - } - if (this.enhancedFilterTools) - { - this.enhancedFilterTools.destroy(); - this.enhancedFilterTools = null; - } - if (this.clearFilterDialog) - { - this.clearFilterDialog.destroyRecursive(); - this.clearFilterDialog = null; - } - if (this.filterStatusTip) - { - this.filterStatusTip.destroy(); - this.filterStatusTip = null; - } - this.args = null; - - }catch(e){ - console.warn("Filter.destroy() error:",e); - } - }, - - _wrapStore: function(){ - var g = this.grid; - var args = this.args; - var filterLayer = args.isServerSide ? new FilterLayer.ServerSideFilterLayer(args) : - new FilterLayer.ClientSideFilterLayer({ - cacheSize: args.filterCacheSize, - fetchAll: args.fetchAllOnFirstFilter, - getter: this._clientFilterGetter - }); - FilterLayer.wrap(g, "_storeLayerFetch", filterLayer); - - this.connect(g, "_onDelete", lang.hitch(filterLayer, "invalidate")); - }, - - onSetStore: function(store){ - this.filterDefDialog.clearFilter(true); - }, - - _clientFilterGetter: function(/* data item */ datarow,/* cell */cell, /* int */rowIndex){ - return cell.get(rowIndex, datarow); - } - - }); - - EnhancedGrid.registerPlugin(EnhancedFilter); - - return EnhancedFilter; - -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/EnhancedFilterTools.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/EnhancedFilterTools.js deleted file mode 100644 index 187ed8cfc6..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/EnhancedFilterTools.js +++ /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. - * - */ - -define([ - "dojo/_base/declare", - "dojo/_base/event", - "dojo/dom-construct", - "dojo/date/locale", - "dijit/form/Button", - "dijit/form/ToggleButton", - "qpid/common/grid/RowNumberLimitDialog", - "qpid/common/grid/ColumnDefDialog", - "qpid/common/grid/FilterSummary", - "qpid/management/UserPreferences" -], function(declare, event, domConstruct, locale, Button, ToggleButton, RowNumberLimitDialog, ColumnDefDialog, FilterSummary, UserPreferences){ - - var _stopEvent = function (evt){ - try{ - if(evt && evt.preventDefault){ - event.stop(evt); - } - }catch(e){} - }; - - return declare("qpid.common.grid.EnhancedFilterTools", null, { - - grid: null, - filterBar: null, - filterStatusTip: null, - clearFilterDialog: null, - filterDefDialog: null, - - columnDefDialog: null, - columnDefButton: null, - filterDefButton: null, - clearFilterButton: null, - filterSummary: null, - setRowNumberLimitButton: null, - setRowNumberLimitDialog: null, - refreshButton: null, - autoRefreshButton: null, - - constructor: function(params) - { - this.inherited(arguments); - - this.filterBar = params.toolbar; - this.grid = params.grid; - this.filterStatusTip= params.filterStatusTip; - this.clearFilterDialog = params.clearFilterDialog; - this.filterDefDialog = params.filterDefDialog; - this.ruleCountToConfirmClearFilter = params.ruleCountToConfirmClearFilter; - this.displayLastUpdateTime = params.hasOwnProperty("displayLastUpdateTime")?params.displayLastUpdateTime:true; - - this._addRefreshButtons(); - this._addRowLimitButton(params.defaulGridRowLimit); - this._addColumnsButton(); - - if (!params.disableFiltering) - { - this._addFilteringTools(params.nls); - } - }, - - toggleClearFilterBtn: function(clearFlag) - { - var filterLayer = this.grid.layer("filter"); - var filterSet = filterLayer && filterLayer.filterDef && filterLayer.filterDef(); - this.clearFilterButton.set("disabled", !filterSet); - }, - - destroy: function() - { - this.inherited(arguments); - - if (this.columnDefDialog) - { - this.columnDefDialog.destroy(); - this.columnDefDialog = null; - } - if (this.columnDefButton) - { - this.columnDefButton.destroy(); - this.columnDefButton = null; - } - if (this.filterDefButton) - { - this.filterDefButton.destroy(); - this.filterDefButton = null; - } - if (this.clearFilterButton) - { - this.clearFilterButton.destroy(); - this.clearFilterButton = null; - } - if (this.filterSummary) - { - this.filterSummary.destroy(); - this.filterSummary = null; - } - if (this.setRowNumberLimitButton) - { - this.setRowNumberLimitButton.destroy(); - this.setRowNumberLimitButton = null; - } - if (this.setRowNumberLimitDialog) - { - this.setRowNumberLimitDialog.destroy(); - this.setRowNumberLimitDialog = null; - } - if (this.refreshButton) - { - this.refreshButton.destroy(); - this.refreshButton = null; - } - if (this.autoRefreshButton) - { - this.autoRefreshButton.destroy(); - this.autoRefreshButton = null; - } - - this.grid = null; - this.filterBar = null; - this.filterStatusTip = null; - this.clearFilterDialog = null; - this.filterDefDialog = null; - }, - - _addRefreshButtons: function() - { - var self = this; - this.refreshButton = new dijit.form.Button({ - label: "Refresh", - type: "button", - iconClass: "gridRefreshIcon", - title: "Manual Refresh" - }); - - this.autoRefreshButton = new dijit.form.ToggleButton({ - label: "Auto Refresh", - type: "button", - iconClass: "gridAutoRefreshIcon", - title: "Auto Refresh" - }); - - this.autoRefreshButton.on("change", function(value){ - self.grid.updater.updatable=value; - self.refreshButton.set("disabled", value); - }); - - this.refreshButton.on("click", function(value){ - self.grid.updater.performUpdate(); - }); - - this.filterBar.addChild(this.autoRefreshButton); - this.filterBar.addChild(this.refreshButton); - - if (this.displayLastUpdateTime) - { - var updateStatusPanel = domConstruct.create("div"); - var updateTimeLabel = domConstruct.create("span", {innerHTML: "Update time: ", "class": "formLabel-labelCell", "style": "padding-right: 5px;padding-left: 5px"}, updateStatusPanel); - var updateTimeLabelPreferredTZ = domConstruct.create("span", {innerHTML: "Preferred timezone:", "style": "padding-right: 5px"}, updateStatusPanel); - var updateTimePreferredTZ = domConstruct.create("span", {"style": "padding-right: 5px"}, updateStatusPanel); - var updateTimeLabelBrowserTZ = domConstruct.create("span", {innerHTML: "Browser timezone:", "style": "padding-right: 5px"}, updateStatusPanel); - var updateTimeBrowserTZ = domConstruct.create("span", {"style": "padding-right: 5px"}, updateStatusPanel); - - var lastUpdateTimeUpdater = function(data) - { - var userTimeZone = UserPreferences.timeZone; - var displayStyle = userTimeZone? "inline" : "none"; - updateTimeLabelPreferredTZ.style.display = displayStyle; - updateTimePreferredTZ.style.display = displayStyle; - var formatOptions = {selector: "time", timePattern: "HH:mm:ss.SSS", appendTimeZone: true, addOffset: true}; - var updateTime = new Date(); - updateTimePreferredTZ.innerHTML = UserPreferences.formatDateTime(updateTime.getTime(), formatOptions); - updateTimeBrowserTZ.innerHTML = locale.format(updateTime, formatOptions); - }; - - if (self.grid.updater.store) - { - // data have been already provided/or fetched - // set last update time to current time - lastUpdateTimeUpdater(); - } - - self.grid.updater.addOnUpdate(lastUpdateTimeUpdater); - domConstruct.place(updateStatusPanel, this.grid.viewsHeaderNode, "before"); - } - }, - - _addRowLimitButton: function(defaulGridRowLimit) - { - var self = this; - this.setRowNumberLimitButton = new dijit.form.Button({ - label: "Set Row Limit", - type: "button", - iconClass: "rowNumberLimitIcon", - title: "Set Row Number Limit" - }); - this.setRowNumberLimitButton.set("title", "Set Row Number Limit (Current: " + defaulGridRowLimit +")"); - - this.setRowNumberLimitDialog = new RowNumberLimitDialog(this.grid.domNode, function(newLimit){ - if (newLimit > 0 && self.grid.updater.appendLimit != newLimit ) - { - self.grid.updater.appendLimit = newLimit; - self.grid.updater.performRefresh([]); - self.setRowNumberLimitButton.set("title", "Set Row Number Limit (Current: " + newLimit +")"); - } - }); - - this.setRowNumberLimitButton.on("click", function(evt){ - self.setRowNumberLimitDialog.showDialog(self.grid.updater.appendLimit); - }); - - this.filterBar.addChild(this.setRowNumberLimitButton); - }, - - _addColumnsButton: function() - { - var self = this; - this.columnDefDialog = new ColumnDefDialog({grid: this.grid}); - - this.columnDefButton = new dijit.form.Button({ - label: "Display Columns", - type: "button", - iconClass: "columnDefDialogButtonIcon", - title: "Show/Hide Columns" - }); - - this.columnDefButton.on("click", function(e){ - _stopEvent(e); - self.columnDefDialog.showDialog(); - }); - - this.filterBar.addChild(this.columnDefButton); - }, - - _addFilteringTools: function(nls) - { - var self = this; - - this.filterDefButton = new dijit.form.Button({ - "class": "dojoxGridFBarBtn", - label: "Set Filter", - iconClass: "dojoxGridFBarDefFilterBtnIcon", - showLabel: "true", - title: "Define filter" - }); - - this.clearFilterButton = new dijit.form.Button({ - "class": "dojoxGridFBarBtn", - label: "Clear filter", - iconClass: "dojoxGridFBarClearFilterButtontnIcon", - showLabel: "true", - title: "Clear filter", - disabled: true - }); - - - this.filterDefButton.on("click", function(e){ - _stopEvent(e); - - // a bit of a hack to force dialog to rebuild the criteria controls in order to get rid from empty rule controls - self.filterDefDialog._criteriasChanged = true; - self.filterDefDialog.showDialog(); - }); - - this.clearFilterButton.on("click", function(e){ - _stopEvent(e); - if (self.ruleCountToConfirmClearFilter && self.filterDefDialog.getCriteria() >= self.ruleCountToConfirmClearFilter) - { - self.clearFilterDialog.show(); - } - else - { - self.grid.layer("filter").filterDef(null); - self.toggleClearFilterBtn(true) - } - }); - - this.filterSummary = new FilterSummary({grid: this.grid, filterStatusTip: this.filterStatusTip, nls: nls}); - - this.filterBar.addChild(this.filterDefButton); - this.filterBar.addChild(this.clearFilterButton); - - this.filterBar.addChild(new dijit.ToolbarSeparator()); - this.filterBar.addChild(this.filterSummary, "last"); - this.filterBar.getColumnIdx = function(coordX){return self.filterSummary._getColumnIdx(coordX);}; - - } - }); -}); \ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/FilterSummary.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/FilterSummary.js deleted file mode 100644 index d29e4027df..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/FilterSummary.js +++ /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. - * - */ - -define([ - "dojo/_base/declare", - "dojo/_base/lang", - "dojo/_base/html", - "dojo/query", - "dojo/dom-construct", - "dojo/string", - "dojo/on", - "dijit/_WidgetBase" -], function(declare, lang, html, query, domConstruct, string, on, _WidgetBase){ - -return declare("qpid.common.grid.FilterSummary", [_WidgetBase], { - - domNode: null, - itemName: null, - filterStatusTip: null, - grid: null, - _handle_statusTooltip: null, - _timeout_statusTooltip: 300, - _nls: null, - - constructor: function(params) - { - this.inherited(arguments); - this.itemName = params.itemsName; - this.initialize(params.filterStatusTip, params.grid); - this._nls = params.nls; - }, - - buildRendering: function(){ - this.inherited(arguments); - var itemsName = this.itemName || this._nls["defaultItemsName"]; - var message = string.substitute(this._nls["filterBarMsgNoFilterTemplate"], [0, itemsName ]); - this.domNode = domConstruct.create("span", {innerHTML: message, "class": "dijit dijitReset dijitInline dijitButtonInline", role: "presentation" }); - }, - - postCreate: function(){ - this.inherited(arguments); - on(this.domNode, "mouseenter", lang.hitch(this, this._onMouseEnter)); - on(this.domNode, "mouseleave", lang.hitch(this, this._onMouseLeave)); - on(this.domNode, "mousemove", lang.hitch(this, this._onMouseMove)); - }, - - destroy: function() - { - this.inherited(arguments); - this.itemName = null; - this.filterStatusTip = null; - this.grid = null; - this._handle_statusTooltip = null; - this._filteredClass = null; - this._nls = null; - }, - - initialize: function(filterStatusTip, grid) - { - this.filterStatusTip = filterStatusTip; - this.grid = grid; - if (this.grid) - { - var filterLayer = grid.layer("filter"); - this.connect(filterLayer, "onFiltered", this.onFiltered); - } - }, - - onFiltered: function(filteredSize, originSize) - { - try - { - var itemsName = this.itemName || this._nls["defaultItemsName"], - msg = "", g = this.grid, - filterLayer = g.layer("filter"); - if(filterLayer.filterDef()){ - msg = string.substitute(this._nls["filterBarMsgHasFilterTemplate"], [filteredSize, originSize, itemsName]); - }else{ - msg = string.substitute(this._nls["filterBarMsgNoFilterTemplate"], [originSize, itemsName]); - } - this.domNode.innerHTML = msg; - } - catch(e) - { - // swallow and log exception - // otherwise grid rendering is screwed - console.error(e); - } - }, - - _getColumnIdx: function(coordX){ - var headers = query("[role='columnheader']", this.grid.viewsHeaderNode); - var idx = -1; - for(var i = headers.length - 1; i >= 0; --i){ - var coord = html.position(headers[i]); - if(coordX >= coord.x && coordX < coord.x + coord.w){ - idx = i; - break; - } - } - if(idx >= 0 && this.grid.layout.cells[idx].filterable !== false){ - return idx; - }else{ - return -1; - } - }, - - _setStatusTipTimeout: function(){ - this._clearStatusTipTimeout(); - this._handle_statusTooltip = setTimeout(lang.hitch(this,this._showStatusTooltip),this._timeout_statusTooltip); - }, - - _clearStatusTipTimeout: function(){ - if (this._handle_statusTooltip){ - clearTimeout(this._handle_statusTooltip); - } - this._handle_statusTooltip = null; - }, - - _showStatusTooltip: function(){ - this._handle_statusTooltip = null; - if(this.filterStatusTip){ - this.filterStatusTip.showDialog(this._tippos.x, this._tippos.y, this._getColumnIdx(this._tippos.x)); - } - }, - - _updateTipPosition: function(evt){ - this._tippos = { - x: evt.pageX, - y: evt.pageY - }; - }, - - _onMouseEnter: function(e){ - this._updateTipPosition(e); - if(this.filterStatusTip){ - this._setStatusTipTimeout(); - } - }, - - _onMouseMove: function(e){ - if(this.filterStatusTip){ - this._setStatusTipTimeout(); - if(this._handle_statusTooltip){ - this._updateTipPosition(e); - } - } - }, - - _onMouseLeave: function(e){ - this._clearStatusTipTimeout(); - } - }); - -}); \ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/GridUpdater.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/GridUpdater.js deleted file mode 100644 index e5d96d44e7..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/GridUpdater.js +++ /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. - * - */ - - -define(["dojo/_base/xhr", - "dojo/parser", - "dojo/_base/array", - "dojo/_base/lang", - "qpid/common/properties", - "qpid/common/updater", - "qpid/common/UpdatableStore", - "qpid/common/util", - "dojo/store/Memory", - "dojo/data/ObjectStore", - "qpid/common/grid/EnhancedFilter", - "dojox/grid/enhanced/plugins/NestedSorting", - "dojo/domReady!"], - function (xhr, parser, array, lang, properties, updater, UpdatableStore, util, Memory, ObjectStore) { - - function GridUpdater(args, store) { - this.updatable = args.hasOwnProperty("updatable") ? args.updatable : true ; - this.serviceUrl = args.serviceUrl; - - this.onUpdate = []; - if (args.onUpdate) - { - this.onUpdate.push(args.onUpdate); - } - this.dataTransformer = args.dataTransformer; - - this.appendData = args.append; - this.appendLimit = args.appendLimit; - this.initialData = args.data; - this.initializeStore(store); - }; - - GridUpdater.prototype.buildUpdatableGridArguments = function(args) - { - var filterPluginFound = args && args.hasOwnProperty("plugins") && args.plugins.filter ? true: false; - - var gridProperties = { - autoHeight: true, - plugins: { - pagination: { - defaultPageSize: 25, - pageSizes: [10, 25, 50, 100], - description: true, - sizeSwitch: true, - pageStepper: true, - gotoButton: true, - maxPageStep: 4, - position: "bottom" - }, - enhancedFilter: { - disableFiltering: filterPluginFound - } - } - }; - - if(args) - { - for(var argProperty in args) - { - if(args.hasOwnProperty(argProperty)) - { - if (argProperty == "plugins") - { - var argPlugins = args[ argProperty ]; - for(var argPlugin in argPlugins) - { - if(argPlugins.hasOwnProperty(argPlugin)) - { - var argPluginProperties = argPlugins[ argPlugin ]; - if (argPluginProperties && gridProperties.plugins.hasOwnProperty(argPlugin)) - { - var gridPlugin = gridProperties.plugins[ argPlugin ]; - for(var pluginProperty in argPluginProperties) - { - if(argPluginProperties.hasOwnProperty(pluginProperty)) - { - gridPlugin[pluginProperty] = argPluginProperties[pluginProperty]; - } - } - } - else - { - gridProperties.plugins[ argPlugin ] = argPlugins[ argPlugin ]; - } - } - } - } - else - { - gridProperties[ argProperty ] = args[ argProperty ]; - } - } - } - } - - gridProperties.updater = this; - gridProperties.store = this.dataStore; - - return gridProperties; - }; - - GridUpdater.prototype.initializeStore = function(store) - { - var self = this; - - function processData(data) - { - if (self.dataTransformer) - { - data = self.dataTransformer(data); - } - var dataSet = false; - if (!store) - { - store = new ObjectStore({objectStore: new Memory({data: data, idProperty: "id"})}); - dataSet = true; - } - self.dataStore = store - self.store = store; - if (store instanceof ObjectStore) - { - if( store.objectStore instanceof Memory) - { - self.memoryStore = store.objectStore; - } - self.store = store.objectStore - } - - if (data) - { - if ((dataSet || self.updateOrAppend(data)) && self.onUpdate.length > 0) - { - self.fireUpdate(data); - } - } - }; - - if (this.serviceUrl) - { - var requestUrl = lang.isFunction(this.serviceUrl) ? this.serviceUrl() : this.serviceUrl; - xhr.get({url: requestUrl, sync: true, handleAs: "json"}).then(processData, util.xhrErrorHandler); - } - else - { - processData(this.initialData); - } - }; - - GridUpdater.prototype.start = function(grid) - { - this.grid = grid; - if (this.serviceUrl) - { - updater.add(this); - } - }; - - GridUpdater.prototype.destroy = function() - { - updater.remove(this); - if (this.dataStore) - { - this.dataStore.close(); - this.dataStore = null; - } - this.store = null; - this.memoryStore = null; - this.grid = null; - this.onUpdate = null; - }; - - GridUpdater.prototype.updateOrAppend = function(data) - { - return this.appendData ? - UpdatableStore.prototype.append.call(this, data, this.appendLimit): - UpdatableStore.prototype.update.call(this, data); - }; - - GridUpdater.prototype.refresh = function(data) - { - if (this.dataTransformer && data) - { - data = this.dataTransformer(data); - } - this.updating = true; - try - { - if (this.updateOrAppend(data)) - { - // EnhancedGrid with Filter plugin has "filter" layer. - // The filter expression needs to be re-applied after the data update - var filterLayer = this.grid.layer("filter"); - if ( filterLayer && filterLayer.filterDef) - { - var currentFilter = filterLayer.filterDef(); - - if (currentFilter) - { - // re-apply filter in the filter layer - filterLayer.filterDef(currentFilter); - } - } - - // refresh grid to render updates - this.grid._refresh(); - } - } - finally - { - this.updating = false; - this.fireUpdate(data); - } - } - - GridUpdater.prototype.update = function() - { - if (this.updatable) - { - this.performUpdate(); - } - }; - - GridUpdater.prototype.performUpdate = function() - { - var self = this; - var requestUrl = lang.isFunction(this.serviceUrl) ? this.serviceUrl() : this.serviceUrl; - var requestArguments = {url: requestUrl, sync: properties.useSyncGet, handleAs: "json"}; - xhr.get(requestArguments).then(function(data){self.refresh(data);}); - }; - - GridUpdater.prototype.performRefresh = function(data) - { - if (!this.updating) - { - this.refresh(data); - } - }; - - GridUpdater.prototype.fireUpdate=function(data) - { - if (this.onUpdate.length > 0) - { - for(var i=0; i 0) - { - try - { - limitChangedCallback(self.rowNumberLimit.value); - } - catch(e) - { - console.error(e); - } - finally - { - self.dialog.hide(); - } - } - }); - - this.closeButton.on("click", function(e){self.dialog.hide(); }); - this.dialog.startup(); - }, - - destroy: function(){ - this.submitButton.destroy(); - this.closeButton.destroy(); - this.dialog.destroy(); - this.dialog = null; - }, - - showDialog: function(currentLimit){ - this.rowNumberLimit.set("value", currentLimit); - this.dialog.show(); - } - - }); - -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/UpdatableGrid.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/UpdatableGrid.js deleted file mode 100644 index 04041388bd..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/grid/UpdatableGrid.js +++ /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. - * - */ - -define([ - "dojo/_base/declare", - "dojox/grid/EnhancedGrid", - "dojo/domReady!"], function(declare, EnhancedGrid){ - - return declare("qpid.common.grid.UpdatableGrid", [EnhancedGrid], { - - updater: null, - - postCreate: function(){ - this.inherited(arguments); - if (this.updater) - { - this.updater.start(this); - } - }, - - destroy: function(){ - if (this.updater) - { - try - { - this.updater.destroy(); - } - catch(e) - { - console.error(e) - } - this.updater = null; - } - this.inherited(arguments); - } - }); - -}); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/metadata.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/metadata.js deleted file mode 100644 index 1a9ceb7419..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/metadata.js +++ /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. - */ -define(["dojo/_base/xhr", - "dojo/_base/array", - "dojox/lang/functional/object", - "qpid/common/properties", - "dojo/domReady!" - ], - function (xhr, array, fobject, properties) - { - var metadata = - { - _init: function () - { - var that = this; - xhr.get({sync: true, handleAs: "json", url: "service/metadata", load: function(data){that._onMetadata(data)}}); - }, - _onMetadata: function (metadata) - { - this.metadata = metadata; - }, - getMetaData: function (category, type) - { - return this.metadata[category][type]; - }, - getDefaultValueForAttribute: function (category, type, attributeName) - { - var metaDataForInstance = this.getMetaData(category, type); - var attributesForType = metaDataForInstance["attributes"]; - var attributesForName = attributesForType[attributeName]; - return attributesForName ? attributesForName["defaultValue"] : undefined; - }, - getTypesForCategory: function (category) - { - return fobject.keys(this.metadata[category]); - }, - extractUniqueListOfValues : function(data) - { - var values = []; - for (i = 0; i < data.length; i++) - { - for (j = 0; j < data[i].length; j++) - { - var current = data[i][j]; - if (array.indexOf(values, current) == -1) - { - values.push(current); - } - } - } - return values; - }, - implementsManagedInterface: function (category, type, managedInterfaceName) - { - var md = this.getMetaData(category, type); - if (md && md.managedInterfaces) - { - return array.indexOf(md.managedInterfaces, managedInterfaceName) >= 0 ; - } - return false; - }, - validChildTypes: function (category, type, childCategory) - { - var metaData = this.getMetaData(category, type); - return metaData ? metaData.validChildTypes[childCategory] : []; - } - - }; - - metadata._init(); - - return metadata; - }); diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/properties.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/properties.js deleted file mode 100644 index 8d85345b74..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/properties.js +++ /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. - * - */ -define(["dojo/has", "dojo/_base/sniff", "dojo/domReady!"], - function (has) { - var properties = {}; - properties.useSyncGet = (has("ie") <= 8); - return properties; - }); \ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/timezone.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/timezone.js deleted file mode 100644 index f886a72daa..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/timezone.js +++ /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. - * - */ - -define(["dojo/_base/xhr"], function (xhr) { - - var timezones = {}; - - var timeZoneSortFunction = function(a, b){ - if (a.region == b.region) - { - if (a.city == b.city) - { - return 0; - } - return a.city < b.city ? -1 : 1; - } - return a.region < b.region ? -1 : 1; - } - - function loadTimezones() - { - xhr.get({ - url: "service/helper?action=ListTimeZones", - sync: true, - handleAs: "json", - load: function(zones) - { - zones.sort(timeZoneSortFunction); - timezones.data = zones; - }, - error: function(error) - { - if (console && console.error) - { - console.error(error); - } - } - }); - } - - return { - getAllTimeZones: function() - { - if (!timezones.data) - { - loadTimezones(); - } - return timezones.data; - }, - getTimeZoneInfo: function(timeZone) { - if (timeZone == "UTC") - { - return { - "id" : "UTC", - "name" : "UTC", - "offset" : 0 - } - } - var tzi = timezones[timeZone]; - if (!tzi) - { - var data = this.getAllTimeZones(); - for(var i = 0; i < data.length; i++) - { - var zone = data[i]; - if (zone.id == timeZone) - { - tzi = zone; - timezones[timeZone] = zone; - break; - } - } - } - return tzi; - } - }; -}); \ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/updater.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/updater.js deleted file mode 100644 index f31fd1aa1f..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/updater.js +++ /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. - * - */ -define(["qpid/management/UserPreferences"], function (UserPreferences) { - var updateList = new Array(); - - function invokeUpdates() - { - for(var i = 0; i < updateList.length; i++) - { - var obj = updateList[i]; - obj.update(); - } - } - - var updatePeriod = UserPreferences.updatePeriod ? UserPreferences.updatePeriod: 5; - - var timer = setInterval(invokeUpdates, updatePeriod * 1000); - - var updateIntervalListener = { - onPreferencesChange: function(preferences) - { - if (preferences.updatePeriod && preferences.updatePeriod != updatePeriod) - { - updatePeriod = preferences.updatePeriod; - clearInterval(timer); - timer = setInterval(invokeUpdates, updatePeriod * 1000); - } - } - }; - - UserPreferences.addListener(updateIntervalListener); - - return { - add: function(obj) { - updateList.push(obj); - }, - - remove: function(obj) { - for(var i = 0; i < updateList.length; i++) { - if(updateList[i] === obj) { - updateList.splice(i,1); - return; - } - } - } - }; -}); \ No newline at end of file diff --git a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/util.js b/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/util.js deleted file mode 100644 index 5bf5574347..0000000000 --- a/qpid/java/broker-plugins/management-http/src/main/java/resources/js/qpid/common/util.js +++ /dev/null @@ -1,842 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -define(["dojo/_base/xhr", - "dojo/_base/array", - "dojo/_base/event", - "dojo/_base/lang", - "dojo/json", - "dojo/dom-construct", - "dojo/dom-geometry", - "dojo/dom-style", - "dojo/_base/window", - "dojo/query", - "dojo/parser", - "dojo/store/Memory", - "dojo/window", - "dojo/on", - "dojox/html/entities", - "qpid/common/metadata", - "qpid/common/widgetconfigurer", - "dijit/registry", - "dijit/TitlePane", - "dijit/Dialog", - "dijit/form/Form", - "dijit/form/Button", - "dijit/form/RadioButton", - "dijit/form/CheckBox", - "dijit/form/FilteringSelect", - "dijit/form/ValidationTextBox", - "dojox/layout/TableContainer", - "dijit/layout/ContentPane", - "dojox/validate/us", - "dojox/validate/web", - "dojo/domReady!" - ], - function (xhr, array, event, lang, json, dom, geometry, domStyle, win, query, parser, Memory, w, on, entities, metadata, widgetconfigurer, registry) { - var util = {}; - if (Array.isArray) { - util.isArray = function (object) { - return Array.isArray(object); - }; - } else { - util.isArray = function (object) { - return object instanceof Array; - }; - } - - util.flattenStatistics = function (data) { - var attrName, stats, propName, theList; - for(attrName in data) { - if(data.hasOwnProperty(attrName)) { - if(attrName == "statistics") { - stats = data.statistics; - for(propName in stats) { - if(stats.hasOwnProperty( propName )) { - data[ propName ] = stats[ propName ]; - } - } - } else if(data[ attrName ] instanceof Array) { - theList = data[ attrName ]; - - for(var i=0; i < theList.length; i++) { - util.flattenStatistics( theList[i] ); - } - } - } - } - }; - - util.isReservedExchangeName = function(exchangeName) - { - return exchangeName == null || exchangeName == "" || "<>" == exchangeName || exchangeName.indexOf("amq.") == 0 || exchangeName.indexOf("qpid.") == 0; - }; - - util.deleteGridSelections = function(updater, grid, url, confirmationMessageStart, idParam) - { - var data = grid.selection.getSelected(); - var success = false; - if(data.length) - { - var confirmationMessage = null; - if (data.length == 1) - { - confirmationMessage = confirmationMessageStart + " '" + data[0].name + "'?"; - } - else - { - var names = ''; - for(var i = 0; i