From 6da678177a05aaf93ce434d2d697e0690175b5ab Mon Sep 17 00:00:00 2001 From: Robbie Gemmell Date: Mon, 4 Apr 2022 15:28:06 +0100 Subject: [PATCH] ARTEMIS-3758: clean up lots of tests that never run, remove related files + dependencies and some unnecessary deps --- tests/activemq5-unit-tests/pom.xml | 164 +-- .../src/test/java/activemq-partition.xml | 58 - .../src/test/java/activemq.xml | 37 - .../activemq/EmbeddedBrokerTestSupport.java | 16 - .../JmsMultipleBrokersTestSupport.java | 668 --------- .../org/apache/activemq/LoadTestBurnIn.java | 168 --- .../apache/activemq/SpringTestSupport.java | 63 - .../java/org/apache/activemq/TestSupport.java | 6 +- .../activemq/ZeroPrefetchConsumerTest.java | 4 +- .../AdvisoryTempDestinationTests.java | 226 --- .../activemq/advisory/AdvisoryTests.java | 234 --- .../advisory/ConsumerListenerTest.java | 156 -- .../advisory/DestinationListenerTest.java | 129 -- .../advisory/ProducerListenerTest.java | 150 -- .../activemq/advisory/TempDestDeleteTest.java | 152 -- .../activemq/advisory/TempDestLoadTest.java | 112 -- .../advisory/TempQueueMemoryTest.java | 170 --- .../blob/FTPBlobDownloadStrategyTest.java | 107 -- .../org/apache/activemq/blob/FTPBlobTest.java | 73 - .../blob/FTPBlobUploadStrategyTest.java | 73 - .../apache/activemq/blob/FTPTestSupport.java | 115 -- .../activemq/blob/FilesystemBlobTest.java | 103 -- .../activemq/broker/BrokerRedeliveryTest.java | 184 --- .../activemq/broker/BrokerServiceTest.java | 84 -- .../ConcurrentConnectSimulationTest.java | 59 - ...eateDestinationsOnStartupViaXBeanTest.java | 71 - .../broker/DedicatedTaskRunnerBrokerTest.java | 38 - .../broker/DoubleSubscriptionTest.java | 120 -- .../DurablePersistentFalseRestartTest.java | 90 -- .../broker/JdbcXARecoveryBrokerTest.java | 90 -- .../java/org/apache/activemq/broker/Main.java | 85 -- .../broker/MarshallingBrokerTest.java | 76 - .../broker/MessageExpirationTest.java | 276 ---- .../broker/NioQueueSubscriptionTest.java | 132 -- .../activemq/broker/OutOfOrderXMLTest.java | 32 - .../broker/QueueMbeanRestartTest.java | 123 -- .../broker/QueueSubscriptionTest.java | 188 --- .../broker/ReconnectWithJMXEnabledTest.java | 95 -- .../activemq/broker/RecoveryBrokerTest.java | 580 -------- .../broker/RedeliveryRestartTest.java | 293 ---- .../RedeliveryRestartWithExceptionTest.java | 468 ------ .../apache/activemq/broker/SpringTest.java | 107 -- .../broker/TopicSubscriptionTest.java | 163 --- .../activemq/broker/XARecoveryBrokerTest.java | 1251 ----------------- .../broker/advisory/AdvisoryBrokerTest.java | 329 ----- .../AdvisoryDuplexNetworkBridgeTest.java | 48 - .../broker/advisory/AdvisoryJmxTest.java | 88 -- .../advisory/AdvisoryNetworkBridgeTest.java | 127 -- .../activemq/broker/destinations-on-start.xml | 39 - ...exclusive-consumer-startup-destination.xml | 46 - ...tJDBCQueueMasterSlaveLeaseQuiesceTest.java | 84 -- ...bRestartJDBCQueueMasterSlaveLeaseTest.java | 58 - .../ft/DbRestartJDBCQueueMasterSlaveTest.java | 155 -- .../broker/ft/DbRestartJDBCQueueTest.java | 165 --- .../broker/ft/JDBCQueueMasterSlaveTest.java | 111 -- .../ft/QueueMasterSlaveSingleUrlTest.java | 94 -- .../ft/QueueMasterSlaveTestSupport.java | 156 -- ...eueMasterSlaveTestUsingSharedFileTest.java | 47 - .../broker/ft/SyncCreateDataSource.java | 89 -- .../kahaDbJdbcLeaseQueueMasterSlaveTest.java | 120 -- .../ft/mKahaDbQueueMasterSlaveTest.java | 94 -- .../activemq/broker/ft/sharedFileMaster.xml | 34 - .../activemq/broker/ft/sharedFileSlave.xml | 35 - .../broker/mKahaDBXARecoveryBrokerTest.java | 64 - .../broker/mLevelDBXARecoveryBrokerTest.java | 73 - .../security/MessageAuthenticationTest.java | 100 -- .../broker/out-of-order-broker-elements.xml | 50 - .../partition/SpringPartitionBrokerTest.java | 53 - .../policy/AbortSlowAckConsumer0Test.java | 177 --- .../policy/AbortSlowAckConsumer1Test.java | 71 - .../policy/AbortSlowAckConsumer2Test.java | 71 - .../broker/policy/AbortSlowConsumer0Test.java | 240 ---- .../broker/policy/AbortSlowConsumer1Test.java | 100 -- .../broker/policy/AbortSlowConsumer2Test.java | 54 - .../broker/policy/AbortSlowConsumerBase.java | 80 -- .../broker/policy/DeadLetterTest.java | 99 -- .../broker/policy/DeadLetterTestSupport.java | 213 --- .../policy/DestinationCursorConfigTest.java | 75 - .../DiscardingDeadLetterPolicyTest.java | 78 - .../policy/IndividualDeadLetterTest.java | 109 -- .../IndividualDeadLetterViaXmlTest.java | 50 - .../broker/policy/MessageGroupConfigTest.java | 91 -- .../policy/MessageListenerDeadLetterTest.java | 153 -- .../policy/NoConsumerDeadLetterTest.java | 116 -- .../broker/policy/NoRetryDeadLetterTest.java | 33 - .../PerDurableConsumerDeadLetterTest.java | 70 - .../PriorityNetworkDispatchPolicyTest.java | 81 -- .../policy/RoundRobinDispatchPolicyTest.java | 135 -- .../activemq/broker/policy/SecureDLQTest.java | 139 -- .../policy/SimpleDispatchPolicyTest.java | 91 -- .../policy/StrictOrderDispatchPolicyTest.java | 131 -- .../apache/activemq/broker/policy/cursor.xml | 67 - .../activemq/broker/policy/individual-dlq.xml | 60 - .../broker/region/DestinationGCTest.java | 112 -- .../region/DestinationRemoveRestartTest.java | 116 -- .../region/QueueDuplicatesFromStoreTest.java | 404 ------ .../QueueOptimizedDispatchExceptionTest.java | 253 ---- .../broker/region/QueuePurgeTest.java | 209 --- .../region/QueueResendDuringShutdownTest.java | 249 ---- .../SubscriptionAddRemoveQueueTest.java | 433 ------ ...uePropertyMessageEvictionStrategyTest.java | 105 -- .../region/cursors/CursorDurableTest.java | 62 - .../region/cursors/CursorQueueStoreTest.java | 79 -- .../broker/region/cursors/CursorSupport.java | 199 --- .../FilePendingMessageCursorTestSupport.java | 90 -- .../region/cursors/OrderPendingListTest.java | 454 ------ .../cursors/PrioritizedPendingListTest.java | 308 ---- .../region/cursors/StoreBasedCursorTest.java | 162 --- .../StoreQueueCursorJDBCNoDuplicateTest.java | 38 - ...StoreQueueCursorKahaDBNoDuplicateTest.java | 40 - ...toreQueueCursorLevelDBNoDuplicateTest.java | 39 - ...StoreQueueCursorMemoryNoDuplicateTest.java | 34 - .../StoreQueueCursorNoDuplicateTest.java | 129 -- .../cursors/StoreQueueCursorOrderTest.java | 507 ------- .../group/MessageGroupHashBucketTest.java | 30 - .../region/group/MessageGroupMapTest.java | 106 -- .../broker/region/group/MessageGroupTest.java | 179 --- .../scheduler/JmsCronSchedulerTest.java | 117 -- .../broker/scheduler/JmsSchedulerTest.java | 286 ---- .../JobSchedulerBrokerShutdownTest.java | 77 - .../JobSchedulerJmxManagementTests.java | 154 -- .../scheduler/JobSchedulerManagementTest.java | 408 ------ .../JobSchedulerStoreCheckpointTest.java | 125 -- .../scheduler/JobSchedulerStoreTest.java | 77 - .../broker/scheduler/JobSchedulerTest.java | 297 ---- .../scheduler/JobSchedulerTestSupport.java | 115 -- .../broker/scheduler/JobSchedulerTxTest.java | 106 -- .../KahaDBSchedulerIndexRebuildTest.java | 195 --- ...KahaDBSchedulerMissingJournalLogsTest.java | 204 --- .../scheduler/LostScheduledMessagesTest.java | 152 -- .../scheduler/SchedulerDBVersionTest.java | 164 --- .../memory/InMemeoryJmsSchedulerTest.java | 40 - .../memory/InMemoryJmsCronSchedulerTest.java | 30 - ...nMemoryJobSchedulerJmxManagementTests.java | 30 - .../InMemoryJobSchedulerManagementTest.java | 30 - .../memory/InMemoryJobSchedulerStoreTest.java | 74 - .../memory/InMemoryJobSchedulerTest.java | 36 - .../memory/InMemoryJobSchedulerTxTest.java | 30 - .../org/apache/activemq/broker/spring.xml | 97 -- .../broker/store/DefaultStoreBrokerTest.java | 49 - .../store/DefaultStoreRecoveryBrokerTest.java | 50 - .../activemq/broker/store/LoadTester.java | 108 -- .../store/RecoverExpiredMessagesTest.java | 144 -- .../activemq/broker/store/kahabroker.xml | 38 - .../activemq/broker/store/loadtester.xml | 61 - .../broker/util/DestinationsPluginTest.java | 77 - .../broker/util/PluginBrokerTest.java | 91 -- .../broker/util/RedeliveryPluginTest.java | 75 - .../util/TimeStampingBrokerPluginTest.java | 202 --- .../util/TraceBrokerPathPluginTest.java | 130 -- .../activemq/config/BrokerPropertiesTest.java | 62 - .../config/BrokerXmlConfigFromJNDITest.java | 53 - .../activemq/config/BrokerXmlConfigTest.java | 50 - .../apache/activemq/config/ConfigTest.java | 423 ------ .../ConfigUsingDestinationOptionsTest.java | 76 - .../activemq/config/JDBCConfigTest.java | 102 -- .../apache/activemq/config/broker.properties | 21 - .../org/apache/activemq/config/config.xml | 31 - .../org/apache/activemq/config/example.xml | 104 -- .../sample-conf/connector-properties.xml | 37 - .../config/sample-conf/jdbc-example.xml | 52 - .../config/sample-conf/journal-example.xml | 60 - .../sample-conf/journaledjdbc-example.xml | 36 - .../config/sample-conf/memory-example.xml | 37 - .../apache/activemq/config/spring-test.xml | 35 - .../activemq/console/command/AMQ3410Test.java | 183 --- .../activemq/console/command/AMQ3411Test.java | 196 --- .../command/DummyConnectionFactory.java | 45 - .../command/InvalidConnectionFactory.java | 23 - .../command/LowercasingPasswordFactory.java | 26 - .../console/command/PurgeCommandTest.java | 427 ------ .../activemq/console/command/activemq.xml | 77 - .../filter/DestinationFilterTest.java | 65 - .../filter/DestinationMapMemoryTest.java | 53 - .../DestinationMapTempDestinationTest.java | 45 - .../activemq/filter/DestinationMapTest.java | 431 ------ .../activemq/filter/DestinationPathTest.java | 36 - .../apache/activemq/filter/DummyPolicy.java | 38 - .../activemq/filter/DummyPolicyEntry.java | 44 - .../activemq/filter/DummyPolicyTest.java | 44 - .../apache/activemq/filter/dummyPolicy.xml | 37 - .../apache/activemq/jmx/JmxCreateNCTest.java | 65 - .../activemq/jmx/OpenTypeSupportTest.java | 115 -- .../ActiveMQInitialContextFactoryTest.java | 72 - .../ActiveMQWASInitialContextFactoryTest.java | 41 - .../jndi/CustomConnectionFactoryNameTest.java | 54 - .../jndi/DestinationNameWithSlashTest.java | 34 - .../activemq/jndi/InitialContextTest.java | 93 -- .../apache/activemq/jndi/JNDITestSupport.java | 99 -- .../activemq/jndi/ObjectFactoryTest.java | 89 -- .../jndi/XAConnectionFactoryTest.java | 33 - .../activemq/joramtests/ActiveMQAdmin.java | 169 --- .../activemq/joramtests/JoramJmsTest.java | 74 - .../leveldb/LevelDBStoreBrokerTest.java | 63 - .../leveldb/LevelDBXARecoveryBrokerTest.java | 68 - .../org/apache/activemq/load/LoadClient.java | 206 --- .../apache/activemq/load/LoadController.java | 101 -- .../org/apache/activemq/load/LoadTest.java | 156 -- .../management/BoundaryStatisticTest.java | 37 - .../management/BoundedRangeStatisticTest.java | 38 - .../management/CountStatisticTest.java | 56 - .../management/RangeStatisticTest.java | 77 - .../management/StatisticTestSupport.java | 45 - .../management/TimeStatisticTest.java | 73 - .../activemq/memory/MemoryPropertyTest.java | 74 - .../org/apache/activemq/memory/activemq.xml | 51 - .../activemq/memory/buffer/DummyMessage.java | 42 - .../buffer/MemoryBufferTestSupport.java | 67 - .../buffer/OrderBasedMemoryBufferTest.java | 70 - .../buffer/SizeBasedMessageBufferTest.java | 53 - .../apache/activemq/memory/usage.properties | 19 - .../BrokerNetworkWithStuckMessagesTest.java | 626 --------- .../CheckDuplicateMessagesOnDuplexTest.java | 359 ----- .../network/CompressionOverNetworkTest.java | 333 ----- .../DemandForwardingBridgeFilterTest.java | 194 --- .../network/DemandForwardingBridgeTest.java | 177 --- .../network/DuplexNetworkMBeanTest.java | 167 --- .../activemq/network/DuplexNetworkTest.java | 60 - ...IncludedDestinationsDuplexNetworkTest.java | 113 -- .../network/FailoverStaticNetworkTest.java | 467 ------ .../network/ForwardingBridgeTest.java | 152 -- .../MQTTNetworkOfBrokersFailoverTest.java | 248 ---- .../network/MulticastNetworkTest.java | 40 - .../network/NetworkBrokerDetachTest.java | 300 ---- .../network/NetworkConnectionsTest.java | 251 ---- .../network/NetworkDestinationFilterTest.java | 45 - .../activemq/network/NetworkFailoverTest.java | 225 --- .../activemq/network/NetworkLoadTest.java | 336 ----- .../activemq/network/NetworkLoopBackTest.java | 65 - .../network/NetworkReconnectTest.java | 329 ----- .../NetworkRemovesSubscriptionsTest.java | 191 --- .../network/NetworkRestartPlainTest.java | 25 - .../activemq/network/NetworkRestartTest.java | 190 --- .../activemq/network/NetworkRouteTest.java | 342 ----- .../SSHTunnelNetworkReconnectTest.java | 91 -- .../activemq/network/SimpleNetworkTest.java | 322 ----- .../duplexDynamicIncludedDestLocalBroker.xml | 54 - .../activemq/network/duplexLocalBroker.xml | 49 - .../QueueBridgeStandaloneReconnectTest.java | 365 ----- .../activemq/network/jms/QueueBridgeTest.java | 114 -- .../network/jms/QueueBridgeXBeanTest.java | 45 - .../jms/QueueOutboundBridgeReconnectTest.java | 342 ----- .../network/jms/TopicBridgeSpringTest.java | 110 -- .../TopicBridgeStandaloneReconnectTest.java | 362 ----- .../network/jms/TopicBridgeXBeanTest.java | 33 - .../jms/TopicOutboundBridgeReconnectTest.java | 329 ----- .../activemq/network/jms/queue-config.xml | 85 -- .../activemq/network/jms/queue-xbean.xml | 72 - .../activemq/network/jms/topic-config.xml | 85 -- .../activemq/network/jms/topic-spring.xml | 85 -- .../activemq/network/localBroker-plain.xml | 36 - .../apache/activemq/network/localBroker.xml | 50 - .../network/multicast/localBroker.xml | 42 - .../network/multicast/remoteBroker.xml | 43 - .../activemq/network/reconnect-broker1.xml | 52 - .../activemq/network/reconnect-broker2.xml | 53 - .../apache/activemq/network/remoteBroker.xml | 38 - .../network/ssh-reconnect-broker1.xml | 53 - .../network/ssh-reconnect-broker2.xml | 54 - .../activemq/perf/ConnectionChurnTest.java | 103 -- .../perf/InactiveDurableTopicTest.java | 191 --- .../activemq/perf/InactiveQueueTest.java | 115 -- .../activemq/perf/KahaDBDurableTopicTest.java | 52 - .../KahaDBDurableTransactedTopicTest.java | 45 - .../apache/activemq/perf/KahaDBQueueTest.java | 65 - .../apache/activemq/perf/KahaQueueTest.java | 40 - .../perf/LevelDBDurableTopicTest.java | 44 - .../activemq/perf/LevelDBStoreQueueTest.java | 43 - .../activemq/perf/MemoryAllocationTest.java | 117 -- .../activemq/perf/NetworkedSyncTest.java | 305 ---- .../perf/NumberOfDestinationsTest.java | 132 -- .../apache/activemq/perf/PerfConsumer.java | 143 -- .../apache/activemq/perf/PerfProducer.java | 134 -- .../org/apache/activemq/perf/PerfRate.java | 81 -- .../perf/QueueConnectionMemoryTest.java | 84 -- .../org/apache/activemq/perf/RunBroker.java | 66 - .../perf/SimpleDurableTopicNetworkTest.java | 49 - .../activemq/perf/SimpleDurableTopicTest.java | 78 - .../activemq/perf/SimpleNetworkTest.java | 143 -- .../SimpleNonPersistentQueueNetworkTest.java | 91 -- .../perf/SimpleNonPersistentQueueTest.java | 81 -- .../perf/SimpleNonPersistentTopicTest.java | 38 - .../apache/activemq/perf/SimpleQueueTest.java | 54 - .../apache/activemq/perf/SimpleTopicTest.java | 209 --- .../apache/activemq/perf/SlowConsumer.java | 52 - .../activemq/perf/SlowConsumerTopicTest.java | 82 -- .../perf/SlowDurableConsumerTopicTest.java | 35 - .../TemporaryTopicMemoryAllocationTest.java | 36 - .../org/apache/activemq/perf/kahaBroker.xml | 31 - .../org/apache/activemq/perf/kahadbBroker.xml | 30 - .../org/apache/activemq/perf/networkSync.xml | 49 - .../activemq/perf/slowConsumerBroker.xml | 41 - .../plugin/BrokerStatisticsPluginTest.java | 213 --- .../plugin/statistics-plugin-broker.xml | 36 - ...TwoConnectionsWithSenderUsingPoolTest.java | 49 - .../apache/activemq/proxy/AMQ4889Test.java | 134 -- .../activemq/proxy/ProxyConnectorTest.java | 105 -- .../activemq/proxy/ProxyFailoverTest.java | 97 -- .../activemq/proxy/ProxyTestSupport.java | 141 -- .../org/apache/activemq/security/AMQauth.ldif | 159 --- ...tCachedLDAPAuthorizationMapLegacyTest.java | 424 ------ ...ractCachedLDAPAuthorizationModuleTest.java | 63 - .../security/AuthorizationMapTest.java | 196 --- ...AuthorizationModuleLegacyOpenLDAPTest.java | 101 -- ...chedLDAPAuthorizationModuleLegacyTest.java | 67 - ...edLDAPAuthorizationModuleOpenLDAPTest.java | 106 -- .../CachedLDAPAuthorizationModuleTest.java | 70 - .../CachedLDAPSecurityLegacyTest.java | 133 -- .../security/CachedLDAPSecurityTest.java | 44 - .../org/apache/activemq/security/DoSTest.java | 102 -- ...asCertificateAuthenticationBrokerTest.java | 186 --- .../JaasDualAuthenticationBrokerTest.java | 201 --- .../activemq/security/JaasNetworkTest.java | 84 -- .../security/LDAPAuthenticationTest.java | 75 - .../security/LDAPAuthorizationMap.properties | 33 - .../security/LDAPAuthorizationMapTest.java | 154 -- .../activemq/security/LDAPSecurityTest.java | 150 -- .../activemq/security/SecurityJMXTest.java | 104 -- .../security/SecurityTestSupport.java | 263 ---- .../security/SimpleAnonymousPluginTest.java | 117 -- ...mpleAuthenticationPluginSeparatorTest.java | 129 -- .../SimpleAuthenticationPluginTest.java | 150 -- .../security/SimpleAuthorizationMapTest.java | 29 - .../SimpleSecurityBrokerSystemTest.java | 191 --- .../StubDoNothingCallbackHandler.java | 31 - .../security/StubDualJaasConfiguration.java | 46 - .../security/StubJaasConfiguration.java | 40 - .../activemq/security/StubLoginModule.java | 98 -- .../security/StubSecurityContext.java | 33 - .../activemq/security/XBeanSecurityTest.java | 54 - ...ecurityWithGuestNoCredentialsOnlyTest.java | 142 -- .../security/XBeanSecurityWithGuestTest.java | 140 -- .../security/XBeanSslContextTest.java | 41 - .../security/activemq-apacheds-add.ldif | 47 - .../security/activemq-apacheds-delete.ldif | 40 - .../activemq-apacheds-legacy-add.ldif | 47 - .../activemq-apacheds-legacy-delete.ldif | 38 - .../security/activemq-apacheds-legacy.ldif | 264 ---- .../security/activemq-apacheds-legacy.xml | 49 - .../activemq/security/activemq-apacheds.ldif | 294 ---- .../activemq/security/activemq-apacheds.xml | 49 - .../activemq/security/activemq-ldap-auth.xml | 46 - .../activemq/security/activemq-ldap.xml | 83 -- .../security/activemq-openldap-add.ldif | 47 - .../security/activemq-openldap-delete.ldif | 38 - .../activemq-openldap-legacy-add.ldif | 47 - .../activemq-openldap-legacy-delete.ldif | 38 - .../security/activemq-openldap-legacy.ldif | 281 ---- .../activemq/security/activemq-openldap.ldif | 312 ---- .../activemq/security/activemq-openldap.xml | 64 - .../activemq/security/activemq-sslcontext.xml | 45 - .../apache/activemq/security/activemq.ldif | 241 ---- .../org/apache/activemq/security/broker1.ks | 0 .../org/apache/activemq/security/broker1.ts | 0 .../org/apache/activemq/security/broker1.xml | 72 - .../org/apache/activemq/security/broker2.ks | 0 .../org/apache/activemq/security/broker2.ts | 0 .../org/apache/activemq/security/broker2.xml | 63 - .../org/apache/activemq/security/client.ks | 0 .../org/apache/activemq/security/client.ts | 0 .../apache/activemq/security/dos-broker.xml | 67 - .../activemq/security/groups.properties | 21 - .../jaas-broker-guest-no-creds-only.xml | 56 - .../activemq/security/jaas-broker-guest.xml | 56 - .../apache/activemq/security/jaas-broker.xml | 63 - .../apache/activemq/security/ldap-spring.xml | 213 --- .../security/simple-anonymous-broker.xml | 91 -- .../activemq/security/simple-auth-broker.xml | 99 -- .../security/simple-auth-separator.xml | 100 -- .../activemq/security/sslcontext-client.ts | 0 .../activemq/security/sslcontext-keystore.ks | 0 .../apache/activemq/security/users.properties | 21 - .../activemq/security/users1.properties | 19 - .../activemq/security/users2.properties | 19 - .../activemq/selector/SelectorParserTest.java | 91 -- .../activemq/selector/SelectorTest.java | 394 ------ .../selector/UnknownHandlingSelectorTest.java | 183 --- ...iveMQConnectionFactoryFactoryBeanTest.java | 94 -- .../apache/activemq/spring/ConsumerBean.java | 168 --- .../spring/Spring2XmlNamespacesTest.java | 24 - ...2XmlNamespacesWithoutRemoteSchemaTest.java | 24 - .../activemq/spring/SpringConsumer.java | 115 -- .../activemq/spring/SpringProducer.java | 81 -- .../apache/activemq/spring/SpringTest.java | 98 -- .../activemq/spring/SpringTestSupport.java | 97 -- ...eceiveWithEmbeddedBrokerAndUserIDTest.java | 111 -- ...WithTwoConnectionsAndByteSelectorTest.java | 38 - ...thTwoConnectionsAndEmbeddedBrokerTest.java | 72 - .../TemporaryDestinationToFromNameTest.java | 57 - .../message/NestedMapAndListPropertyTest.java | 93 -- .../test/message/NestedMapMessageTest.java | 97 -- .../test/retroactive/DummyMessageQuery.java | 51 - ...merTestWithDestinationBasedBufferTest.java | 29 - ...stWithLastImagePolicyWithWildcardTest.java | 53 - ...ConsumerTestWithSimpleMessageListTest.java | 127 -- ...oactiveConsumerTestWithTimePolicyTest.java | 29 - ...troactiveConsumerWithMessageQueryTest.java | 114 -- .../retroactive/activemq-fixed-buffer.xml | 46 - .../activemq-fixed-destination-buffer.xml | 46 - .../retroactive/activemq-lastimage-policy.xml | 47 - .../retroactive/activemq-message-query.xml | 48 - .../retroactive/activemq-timed-policy.xml | 47 - .../CloseRollbackRedeliveryQueueTest.java | 138 -- ...elegatingTransactionalMessageListener.java | 74 - ...RollbacksWhileConsumingLargeQueueTest.java | 186 --- .../DiscoveryNetworkReconnectTest.java | 222 --- .../DiscoveryTransportBrokerTest.java | 166 --- .../DiscoveryTransportNoBrokerTest.java | 172 --- .../transport/discovery/DiscoveryUriTest.java | 69 - .../ZeroconfDiscoverTransportTest.java | 30 - .../CompositeMessageCursorUsageTest.java | 95 -- .../usage/JobSchedulerStoreUsageTest.java | 106 -- .../activemq/usage/StoreUsageLimitsTest.java | 75 - .../apache/activemq/usage/StoreUsageTest.java | 73 - .../apache/activemq/usecases/AMQ2927Test.java | 132 -- .../usecases/AMQStackOverFlowTest.java | 148 -- ...ildcardIncludedDestinationTestSupport.java | 153 -- .../usecases/AdvisoryTopicCleanUpTest.java | 164 --- .../usecases/AdvisoryTopicDeletionTest.java | 126 -- .../AuthorizationFromAdminViewTest.java | 68 - .../usecases/BacklogNetworkCrossTalkTest.java | 96 -- .../BatchedMessagePriorityConsumerTest.java | 81 -- .../BrokerQueueNetworkWithDisconnectTest.java | 262 ---- .../activemq/usecases/BrowseDLQTest.java | 108 -- .../usecases/BrowseOverNetworkTest.java | 248 ---- .../usecases/ChangeSentMessageTest.java | 67 - .../ChangeSessionDeliveryModeTest.java | 63 - .../usecases/ClientRebalanceTest.java | 91 -- .../usecases/CompositeConsumeTest.java | 76 - .../usecases/CompositePublishTest.java | 153 -- .../ConcurrentDestinationCreationTest.java | 154 -- ...ConcurrentProducerDurableConsumerTest.java | 476 ------- .../ConcurrentProducerQueueConsumerTest.java | 417 ------ .../usecases/ConsumeQueuePrefetchTest.java | 58 - .../usecases/ConsumeTopicPrefetchTest.java | 155 -- ...sumeUncompressedCompressedMessageTest.java | 188 --- .../CreateLotsOfTemporaryQueuesTest.java | 69 - .../CreateTemporaryQueueBeforeStartTest.java | 134 -- .../DiscriminatingConsumerLoadTest.java | 306 ---- .../DispatchMultipleConsumersTest.java | 232 --- ...rableConsumerCloseAndReconnectTcpTest.java | 212 --- .../DurableConsumerCloseAndReconnectTest.java | 244 ---- .../DurableSubDelayedUnsubscribeTest.java | 774 ---------- .../DurableSubInBrokerNetworkTest.java | 179 --- ...ncurrentCommitActivateNoDuplicateTest.java | 879 ------------ .../DurableSubProcessMultiRestartTest.java | 405 ------ .../usecases/DurableSubProcessTest.java | 678 --------- .../DurableSubProcessWithRestartTest.java | 776 ---------- .../usecases/DurableSubSelectorDelayTest.java | 308 ---- ...urableSubSelectorDelayWithRestartTest.java | 337 ----- ...SelectorConcurrentConsumeIndexUseTest.java | 256 ---- ...urableSubsOfflineSelectorIndexUseTest.java | 232 --- ...bleSubscriberNonPersistentMessageTest.java | 320 ----- ...leSubscriberWithNetworkDisconnectTest.java | 243 ---- ...rableSubscriberWithNetworkRestartTest.java | 232 --- .../DurableSubscriptionActivationTest.java | 125 -- .../DurableSubscriptionHangTestCase.java | 132 -- .../DurableSubscriptionOffline1Test.java | 247 ---- .../DurableSubscriptionOffline2Test.java | 167 --- .../DurableSubscriptionOffline3Test.java | 423 ------ .../DurableSubscriptionOffline4Test.java | 129 -- .../DurableSubscriptionOfflineTest.java | 870 ------------ .../DurableSubscriptionOfflineTestBase.java | 226 --- .../DurableSubscriptionReactivationTest.java | 98 -- .../DurableSubscriptionRemoveOfflineTest.java | 121 -- .../DurableSubscriptionSelectorTest.java | 180 --- .../DurableSubscriptionTestSupport.java | 534 ------- .../DurableSubscriptionUnsubscribeTest.java | 341 ----- .../usecases/DurableUnsubscribeTest.java | 121 -- .../usecases/ExceptionListenerTest.java | 120 -- .../usecases/ExpiredMessagesTest.java | 306 ---- .../ExpiredMessagesWithNoConsumerTest.java | 585 -------- .../usecases/JDBCDurableSubscriptionTest.java | 41 - .../JMXRemoveQueueThenSendIgnoredTest.java | 153 -- .../usecases/JdbcDurableSubDupTest.java | 290 ---- .../JournalDurableSubscriptionTest.java | 39 - .../KahaDBDurableSubscriptionTest.java | 29 - .../usecases/LargeQueueSparseDeleteTest.java | 177 --- .../LevelDBDurableSubscriptionTest.java | 38 - .../ManagedDurableSubscriptionTest.java | 119 -- .../activemq/usecases/MemoryLimitTest.java | 204 --- .../usecases/MessageGroupCloseTest.java | 254 ---- .../usecases/MessageGroupDelayedTest.java | 248 ---- .../MessageGroupLateArrivalsTest.java | 304 ---- .../usecases/MessageGroupNewConsumerTest.java | 185 --- ...MessageGroupReconnectDistributionTest.java | 218 --- .../usecases/MessageReroutingTest.java | 85 -- .../MultiBrokersMultiClientsTest.java | 167 --- .../MultiBrokersMultiClientsUsingTcpTest.java | 88 -- ...MulticastDiscoveryOnFaultyNetworkTest.java | 130 -- .../apache/activemq/usecases/MyObject.java | 68 - .../usecases/NetworkAsyncStartTest.java | 123 -- .../NetworkBridgeProducerFlowControlTest.java | 347 ----- .../usecases/NetworkOfTwentyBrokersTest.java | 225 --- .../NewConsumerCreatesDestinationTest.java | 63 - .../NoDuplicateOnTopicNetworkTest.java | 375 ----- .../NonBlockingConsumerRedeliveryTest.java | 441 ------ .../ObjectMessageNotSerializableTest.java | 277 ---- .../usecases/ProducerConsumerTestSupport.java | 56 - ...lishOnDurableTopicConsumedMessageTest.java | 29 - ...QueueConsumedMessageInTransactionTest.java | 189 --- .../PublishOnQueueConsumedMessageTest.java | 29 - ...ueConsumedMessageUsingActivemqXMLTest.java | 92 -- ...shOnTemporaryQueueConsumedMessageTest.java | 32 - .../PublishOnTopicConsumedMessageTest.java | 69 - ...icConsumerMessageUsingActivemqXMLTest.java | 93 -- .../usecases/QueueBrowsingLevelDBTest.java | 36 - .../usecases/QueueBrowsingLimitTest.java | 112 -- .../activemq/usecases/QueueBrowsingTest.java | 214 --- .../QueueConsumerCloseAndReconnectTest.java | 28 - .../usecases/QueueDuplicatesTest.java | 163 --- .../QueueMemoryFullMultiBrokersTest.java | 101 -- .../activemq/usecases/QueueRedeliverTest.java | 30 - .../activemq/usecases/QueueRepeaterTest.java | 120 -- .../usecases/ReliableReconnectTest.java | 180 --- .../RequestReplyNoAdvisoryNetworkTest.java | 278 ---- ...tReplyTempDestRemovalAdvisoryRaceTest.java | 474 ------- ...stReplyToTopicViaThreeNetworkHopsTest.java | 983 ------------- ...alDestinationsWithWildcardLevelDBTest.java | 35 - ...erVirtualDestinationsWithWildcardTest.java | 130 -- .../usecases/StartAndStopBrokerTest.java | 77 - ...dBrokerDoesNotLeaveThreadsRunningTest.java | 97 -- .../activemq/usecases/StaticNetworkTest.java | 69 - .../SubscribeClosePublishThenConsumeTest.java | 111 -- .../TempTopicProducerFlowControlTest.java | 44 - ...rConnectionDuplexExcludedDestinations.java | 170 --- .../apache/activemq/usecases/TestSupport.java | 149 -- .../usecases/ThreeBrokerQueueNetworkTest.java | 668 --------- .../ThreeBrokerQueueNetworkUsingTcpTest.java | 71 - .../ThreeBrokerStompTemporaryQueueTest.java | 180 --- ...TempDestDemandSubscriptionCleanupTest.java | 262 ---- .../ThreeBrokerTempQueueNetworkTest.java | 121 -- .../usecases/ThreeBrokerTopicNetworkTest.java | 410 ------ .../ThreeBrokerTopicNetworkUsingTcpTest.java | 71 - ...eBrokerVirtualTopicNetworkLevelDBTest.java | 34 - .../ThreeBrokerVirtualTopicNetworkTest.java | 188 --- .../TopicDurableConnectStatsTest.java | 268 ---- .../TopicProducerFlowControlTest.java | 194 --- .../activemq/usecases/TopicRedeliverTest.java | 285 ---- .../usecases/TopicReplicationTest.java | 112 -- .../TopicSubscriptionSlowConsumerTest.java | 123 -- .../TopicSubscriptionZeroPrefetchTest.java | 116 -- .../TransactionRollbackOrderTest.java | 161 --- .../activemq/usecases/TransactionTest.java | 120 -- .../usecases/TransientQueueRedeliverTest.java | 33 - ...sageNotSentToRemoteWhenNoConsumerTest.java | 130 -- .../usecases/TwoBrokerMulticastQueueTest.java | 271 ---- ...ardDynamicallyIncludedDestinationTest.java | 34 - ...cardStaticallyIncludedDestinationTest.java | 34 - .../TwoBrokerNetworkLoadBalanceTest.java | 79 -- .../TwoBrokerQueueClientsReconnectTest.java | 600 -------- .../TwoBrokerQueueSendReceiveTest.java | 61 - .../TwoBrokerTempQueueAdvisoryTest.java | 212 --- ...SendReceiveLotsOfMessagesUsingTcpTest.java | 30 - .../TwoBrokerTopicSendReceiveTest.java | 102 -- ...SendReceiveUsingJavaConfigurationTest.java | 81 -- ...TwoBrokerTopicSendReceiveUsingTcpTest.java | 83 -- ...irtualDestDinamicallyIncludedDestTest.java | 231 --- .../TwoBrokerVirtualTopicForwardingTest.java | 201 --- ...stDiscoveryBrokerTopicSendReceiveTest.java | 44 - .../TwoSecureBrokerRequestReplyTest.java | 89 -- .../usecases/UnlimitedEnqueueTest.java | 137 -- .../VerifyNetworkConsumersDisconnectTest.java | 273 ---- ...alTopicNetworkClusterReactivationTest.java | 176 --- .../org/apache/activemq/usecases/activemq.xml | 108 -- .../activemq/usecases/browse-broker1.xml | 60 - .../activemq/usecases/browse-broker1A.xml | 193 --- .../activemq/usecases/browse-broker1B.xml | 194 --- .../activemq/usecases/browse-broker2.xml | 52 - .../activemq/usecases/browse-broker2A.xml | 193 --- .../activemq/usecases/browse-broker2B.xml | 195 --- .../activemq/usecases/browse-broker3A.xml | 192 --- .../activemq/usecases/browse-broker3B.xml | 191 --- .../activemq/usecases/multicast-broker-1.xml | 44 - .../activemq/usecases/multicast-broker-2.xml | 41 - .../usecases/multicast-broker-auto.xml | 44 - .../activemq/usecases/rebalance-broker1.xml | 30 - .../activemq/usecases/rebalance-broker2.xml | 31 - .../activemq/usecases/rebalance-broker3.xml | 30 - .../usecases/receiver-activecluster.xml | 37 - .../activemq/usecases/receiver-discovery.xml | 44 - .../activemq/usecases/receiver-duplex.xml | 46 - .../activemq/usecases/receiver-http.xml | 41 - .../activemq/usecases/receiver-secured.xml | 78 - .../activemq/usecases/receiver-zeroconf.xml | 42 - .../org/apache/activemq/usecases/receiver.xml | 41 - .../activemq/usecases/replication-broker1.xml | 121 -- .../activemq/usecases/replication-broker2.xml | 120 -- .../activemq/usecases/replication-broker3.xml | 120 -- .../activemq/usecases/replication-broker4.xml | 120 -- .../usecases/rerouting-activemq-A.xml | 54 - .../usecases/rerouting-activemq-B.xml | 41 - .../usecases/rerouting-activemq-C.xml | 42 - .../usecases/rerouting-activemq-D.xml | 45 - .../usecases/sender-activecluster.xml | 42 - .../activemq/usecases/sender-discovery.xml | 43 - .../activemq/usecases/sender-duplex.xml | 63 - .../apache/activemq/usecases/sender-http.xml | 39 - .../activemq/usecases/sender-secured.xml | 82 -- .../activemq/usecases/sender-zeroconf.xml | 42 - .../org/apache/activemq/usecases/sender.xml | 45 - .../apache/activemq/util/LinkedNodeTest.java | 174 --- .../apache/activemq/util/LockFileTest.java | 70 - .../activemq/util/ReflectionSupportTest.java | 119 -- .../apache/activemq/util/plugin-broker.xml | 45 - .../xbean/ConnectorXBeanConfigTest.java | 216 --- ...JDBCPersistenceAdapterXBeanConfigTest.java | 64 - .../xbean/JDBCPersistenceXBeanConfigTest.java | 64 - .../ManagementContextXBeanConfigTest.java | 104 -- ...sWithEmbeddedBrokerAndPersistenceTest.java | 30 - .../MultipleTestsWithEmbeddedBrokerTest.java | 58 - ...ultipleTestsWithSpringFactoryBeanTest.java | 81 -- ...leTestsWithSpringXBeanFactoryBeanTest.java | 44 - ...MultipleTestsWithXBeanFactoryBeanTest.java | 36 - .../activemq/xbean/XBeanConfigTest.java | 125 -- .../activemq/xbean/XBeanStartFalseTest.java | 33 - .../apache/activemq/xbean/XBeanXmlTest.java | 27 - .../apache/activemq/xbean/activemq-policy.xml | 77 - .../org/apache/activemq/xbean/activemq.xml | 65 - .../org/apache/activemq/xbean/activemq2.xml | 56 - .../apache/activemq/xbean/connector-test.xml | 61 - .../xbean/jdbc-persistence-adapter-test.xml | 44 - .../activemq/xbean/jdbc-persistence-test.xml | 42 - .../xbean/management-context-test.xml | 44 - .../java/org/apache/activemq/xbean/spring.xml | 74 - .../org/apache/activemq/xbean/spring2.xml | 24 - .../java/spring-embedded-xbean-bean-ref.xml | 101 -- .../test/java/spring-embedded-xbean-local.xml | 80 -- .../java/spring-embedded-xbean-noversion.xml | 80 -- .../src/test/java/spring-embedded-xbean.xml | 80 -- .../src/test/java/spring-embedded.xml | 83 -- .../src/test/java/spring-jndi.xml | 119 -- .../src/test/java/spring-queue.xml | 86 -- .../src/test/java/spring.xml | 79 -- .../src/test/resources/activemq-partition.xml | 58 - .../src/test/resources/activemq.xml | 37 - .../spring-embedded-xbean-bean-ref.xml | 101 -- .../resources/spring-embedded-xbean-local.xml | 80 -- .../spring-embedded-xbean-noversion.xml | 80 -- .../test/resources/spring-embedded-xbean.xml | 80 -- .../src/test/resources/spring-embedded.xml | 83 -- .../src/test/resources/spring-jndi.xml | 119 -- .../src/test/resources/spring-queue.xml | 86 -- .../src/test/resources/spring-start-false.xml | 55 - .../src/test/resources/spring.xml | 79 -- 645 files changed, 4 insertions(+), 84993 deletions(-) delete mode 100644 tests/activemq5-unit-tests/src/test/java/activemq-partition.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/activemq.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsMultipleBrokersTestSupport.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/LoadTestBurnIn.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/SpringTestSupport.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/AdvisoryTempDestinationTests.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/AdvisoryTests.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/ConsumerListenerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/DestinationListenerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/ProducerListenerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempDestDeleteTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempDestLoadTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempQueueMemoryTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobDownloadStrategyTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobUploadStrategyTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPTestSupport.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FilesystemBlobTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerRedeliveryTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerServiceTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ConcurrentConnectSimulationTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/CreateDestinationsOnStartupViaXBeanTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DedicatedTaskRunnerBrokerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DoubleSubscriptionTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DurablePersistentFalseRestartTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/JdbcXARecoveryBrokerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/Main.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/MarshallingBrokerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/MessageExpirationTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/NioQueueSubscriptionTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/OutOfOrderXMLTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/QueueMbeanRestartTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/QueueSubscriptionTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ReconnectWithJMXEnabledTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RecoveryBrokerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RedeliveryRestartTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RedeliveryRestartWithExceptionTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/SpringTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/TopicSubscriptionTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/XARecoveryBrokerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryBrokerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryDuplexNetworkBridgeTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryJmxTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryNetworkBridgeTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/destinations-on-start.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/exclusive-consumer-startup-destination.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveLeaseQuiesceTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveLeaseTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/JDBCQueueMasterSlaveTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveSingleUrlTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveTestSupport.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveTestUsingSharedFileTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/SyncCreateDataSource.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/kahaDbJdbcLeaseQueueMasterSlaveTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/mKahaDbQueueMasterSlaveTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/sharedFileMaster.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/sharedFileSlave.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/mKahaDBXARecoveryBrokerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/mLevelDBXARecoveryBrokerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/message/security/MessageAuthenticationTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/out-of-order-broker-elements.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/partition/SpringPartitionBrokerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer0Test.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer1Test.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer2Test.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer0Test.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer1Test.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer2Test.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumerBase.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DeadLetterTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DeadLetterTestSupport.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DestinationCursorConfigTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DiscardingDeadLetterPolicyTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/IndividualDeadLetterTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/IndividualDeadLetterViaXmlTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/MessageGroupConfigTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/MessageListenerDeadLetterTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/NoConsumerDeadLetterTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/NoRetryDeadLetterTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/PerDurableConsumerDeadLetterTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/PriorityNetworkDispatchPolicyTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/RoundRobinDispatchPolicyTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/SecureDLQTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/SimpleDispatchPolicyTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/StrictOrderDispatchPolicyTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/cursor.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/individual-dlq.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/DestinationGCTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/DestinationRemoveRestartTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueDuplicatesFromStoreTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueOptimizedDispatchExceptionTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueuePurgeTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueResendDuringShutdownTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/SubscriptionAddRemoveQueueTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/UniquePropertyMessageEvictionStrategyTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorDurableTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorQueueStoreTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorSupport.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/FilePendingMessageCursorTestSupport.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/OrderPendingListTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/PrioritizedPendingListTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreBasedCursorTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorJDBCNoDuplicateTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorKahaDBNoDuplicateTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorLevelDBNoDuplicateTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorMemoryNoDuplicateTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorNoDuplicateTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorOrderTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupHashBucketTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupMapTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JmsCronSchedulerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JmsSchedulerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerBrokerShutdownTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerJmxManagementTests.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerManagementTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerStoreCheckpointTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerStoreTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTestSupport.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTxTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/KahaDBSchedulerIndexRebuildTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/KahaDBSchedulerMissingJournalLogsTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/LostScheduledMessagesTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/SchedulerDBVersionTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemeoryJmsSchedulerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJmsCronSchedulerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerJmxManagementTests.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerManagementTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerStoreTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerTxTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/spring.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/DefaultStoreBrokerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/DefaultStoreRecoveryBrokerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/LoadTester.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/RecoverExpiredMessagesTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/kahabroker.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/loadtester.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/DestinationsPluginTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/PluginBrokerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/RedeliveryPluginTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/TimeStampingBrokerPluginTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/TraceBrokerPathPluginTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerPropertiesTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerXmlConfigFromJNDITest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerXmlConfigTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/ConfigTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/ConfigUsingDestinationOptionsTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/JDBCConfigTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/broker.properties delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/config.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/example.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/sample-conf/connector-properties.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/sample-conf/jdbc-example.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/sample-conf/journal-example.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/sample-conf/journaledjdbc-example.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/sample-conf/memory-example.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/spring-test.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/AMQ3410Test.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/AMQ3411Test.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/DummyConnectionFactory.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/InvalidConnectionFactory.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/LowercasingPasswordFactory.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/PurgeCommandTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/activemq.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationFilterTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapMemoryTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapTempDestinationTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationPathTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicy.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicyEntry.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicyTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/dummyPolicy.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jmx/JmxCreateNCTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jmx/OpenTypeSupportTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ActiveMQInitialContextFactoryTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ActiveMQWASInitialContextFactoryTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/CustomConnectionFactoryNameTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/DestinationNameWithSlashTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/InitialContextTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/JNDITestSupport.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ObjectFactoryTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/XAConnectionFactoryTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/joramtests/ActiveMQAdmin.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/joramtests/JoramJmsTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/leveldb/LevelDBStoreBrokerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/leveldb/LevelDBXARecoveryBrokerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadClient.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadController.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/BoundaryStatisticTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/BoundedRangeStatisticTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/CountStatisticTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/RangeStatisticTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/StatisticTestSupport.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/TimeStatisticTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/MemoryPropertyTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/activemq.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/DummyMessage.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/MemoryBufferTestSupport.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/OrderBasedMemoryBufferTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/SizeBasedMessageBufferTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/usage.properties delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/BrokerNetworkWithStuckMessagesTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/CheckDuplicateMessagesOnDuplexTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/CompressionOverNetworkTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DemandForwardingBridgeFilterTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DemandForwardingBridgeTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DuplexNetworkMBeanTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DuplexNetworkTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DynamicallyIncludedDestinationsDuplexNetworkTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/FailoverStaticNetworkTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/ForwardingBridgeTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/MQTTNetworkOfBrokersFailoverTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/MulticastNetworkTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkBrokerDetachTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkConnectionsTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkDestinationFilterTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkFailoverTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkLoadTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkLoopBackTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkReconnectTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRemovesSubscriptionsTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRestartPlainTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRestartTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRouteTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/SSHTunnelNetworkReconnectTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/SimpleNetworkTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/duplexDynamicIncludedDestLocalBroker.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/duplexLocalBroker.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeStandaloneReconnectTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeXBeanTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueOutboundBridgeReconnectTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeSpringTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeStandaloneReconnectTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeXBeanTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicOutboundBridgeReconnectTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/queue-config.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/queue-xbean.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/topic-config.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/topic-spring.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/localBroker-plain.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/localBroker.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/multicast/localBroker.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/multicast/remoteBroker.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/reconnect-broker1.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/reconnect-broker2.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/remoteBroker.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/ssh-reconnect-broker1.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/ssh-reconnect-broker2.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/ConnectionChurnTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/InactiveDurableTopicTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/InactiveQueueTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBDurableTopicTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBDurableTransactedTopicTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBQueueTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaQueueTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/LevelDBDurableTopicTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/LevelDBStoreQueueTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/MemoryAllocationTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/NetworkedSyncTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/NumberOfDestinationsTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfConsumer.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfProducer.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfRate.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/QueueConnectionMemoryTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/RunBroker.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleDurableTopicNetworkTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleDurableTopicTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNetworkTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentQueueNetworkTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentQueueTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentTopicTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleQueueTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleTopicTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowConsumer.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowConsumerTopicTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowDurableConsumerTopicTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/TemporaryTopicMemoryAllocationTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/kahaBroker.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/kahadbBroker.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/networkSync.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/slowConsumerBroker.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/plugin/BrokerStatisticsPluginTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/plugin/statistics-plugin-broker.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/pool/JmsSendReceiveTwoConnectionsWithSenderUsingPoolTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/AMQ4889Test.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyConnectorTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyFailoverTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyTestSupport.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AMQauth.ldif delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AbstractCachedLDAPAuthorizationMapLegacyTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AbstractCachedLDAPAuthorizationModuleTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AuthorizationMapTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleLegacyOpenLDAPTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleLegacyTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleOpenLDAPTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPSecurityLegacyTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPSecurityTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/DoSTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasCertificateAuthenticationBrokerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasDualAuthenticationBrokerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasNetworkTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPAuthenticationTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPAuthorizationMap.properties delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPAuthorizationMapTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPSecurityTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SecurityJMXTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SecurityTestSupport.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAnonymousPluginTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthenticationPluginSeparatorTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthenticationPluginTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthorizationMapTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleSecurityBrokerSystemTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubDoNothingCallbackHandler.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubDualJaasConfiguration.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubJaasConfiguration.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubLoginModule.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubSecurityContext.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityWithGuestNoCredentialsOnlyTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityWithGuestTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSslContextTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-add.ldif delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-delete.ldif delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-legacy-add.ldif delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-legacy-delete.ldif delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-legacy.ldif delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-legacy.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds.ldif delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-ldap-auth.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-ldap.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap-add.ldif delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap-delete.ldif delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap-legacy-add.ldif delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap-legacy-delete.ldif delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap-legacy.ldif delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap.ldif delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-sslcontext.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq.ldif delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/broker1.ks delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/broker1.ts delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/broker1.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/broker2.ks delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/broker2.ts delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/broker2.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/client.ks delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/client.ts delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/dos-broker.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/groups.properties delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/jaas-broker-guest-no-creds-only.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/jaas-broker-guest.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/jaas-broker.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/ldap-spring.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/simple-anonymous-broker.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/simple-auth-broker.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/simple-auth-separator.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/sslcontext-client.ts delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/sslcontext-keystore.ks delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/users.properties delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/users1.properties delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/users2.properties delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/SelectorParserTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/SelectorTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/UnknownHandlingSelectorTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/ActiveMQConnectionFactoryFactoryBeanTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/ConsumerBean.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/Spring2XmlNamespacesTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/Spring2XmlNamespacesWithoutRemoteSchemaTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringConsumer.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringProducer.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringTestSupport.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithEmbeddedBrokerAndUserIDTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithTwoConnectionsAndByteSelectorTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithTwoConnectionsAndEmbeddedBrokerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/TemporaryDestinationToFromNameTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/message/NestedMapAndListPropertyTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/message/NestedMapMessageTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/DummyMessageQuery.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithDestinationBasedBufferTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithLastImagePolicyWithWildcardTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithSimpleMessageListTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithTimePolicyTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerWithMessageQueryTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/activemq-fixed-buffer.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/activemq-fixed-destination-buffer.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/activemq-lastimage-policy.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/activemq-message-query.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/activemq-timed-policy.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/CloseRollbackRedeliveryQueueTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/DelegatingTransactionalMessageListener.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/RollbacksWhileConsumingLargeQueueTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryNetworkReconnectTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryTransportBrokerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryTransportNoBrokerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryUriTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/ZeroconfDiscoverTransportTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/CompositeMessageCursorUsageTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/JobSchedulerStoreUsageTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/StoreUsageLimitsTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/StoreUsageTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AMQ2927Test.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AMQStackOverFlowTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AbstractTwoBrokerNetworkConnectorWildcardIncludedDestinationTestSupport.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AdvisoryTopicCleanUpTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AdvisoryTopicDeletionTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AuthorizationFromAdminViewTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BacklogNetworkCrossTalkTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BatchedMessagePriorityConsumerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrokerQueueNetworkWithDisconnectTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrowseDLQTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrowseOverNetworkTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ChangeSentMessageTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ChangeSessionDeliveryModeTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ClientRebalanceTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CompositeConsumeTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CompositePublishTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentDestinationCreationTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentProducerDurableConsumerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentProducerQueueConsumerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeQueuePrefetchTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeTopicPrefetchTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeUncompressedCompressedMessageTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CreateLotsOfTemporaryQueuesTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CreateTemporaryQueueBeforeStartTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DiscriminatingConsumerLoadTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DispatchMultipleConsumersTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableConsumerCloseAndReconnectTcpTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableConsumerCloseAndReconnectTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubDelayedUnsubscribeTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubInBrokerNetworkTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessConcurrentCommitActivateNoDuplicateTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessMultiRestartTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessWithRestartTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubSelectorDelayTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubSelectorDelayWithRestartTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubsOfflineSelectorConcurrentConsumeIndexUseTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubsOfflineSelectorIndexUseTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberNonPersistentMessageTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberWithNetworkDisconnectTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberWithNetworkRestartTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionActivationTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionHangTestCase.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline1Test.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline2Test.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline3Test.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline4Test.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOfflineTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOfflineTestBase.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionReactivationTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionRemoveOfflineTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionSelectorTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionTestSupport.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionUnsubscribeTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableUnsubscribeTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExceptionListenerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExpiredMessagesTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExpiredMessagesWithNoConsumerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JDBCDurableSubscriptionTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JMXRemoveQueueThenSendIgnoredTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JdbcDurableSubDupTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JournalDurableSubscriptionTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/KahaDBDurableSubscriptionTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/LargeQueueSparseDeleteTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/LevelDBDurableSubscriptionTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ManagedDurableSubscriptionTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MemoryLimitTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupCloseTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupDelayedTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupLateArrivalsTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupNewConsumerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupReconnectDistributionTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageReroutingTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MultiBrokersMultiClientsTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MultiBrokersMultiClientsUsingTcpTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MulticastDiscoveryOnFaultyNetworkTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MyObject.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkAsyncStartTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkBridgeProducerFlowControlTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkOfTwentyBrokersTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NewConsumerCreatesDestinationTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NoDuplicateOnTopicNetworkTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NonBlockingConsumerRedeliveryTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ObjectMessageNotSerializableTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ProducerConsumerTestSupport.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnDurableTopicConsumedMessageTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageInTransactionTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageUsingActivemqXMLTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTemporaryQueueConsumedMessageTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTopicConsumedMessageTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTopicConsumerMessageUsingActivemqXMLTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingLevelDBTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingLimitTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueConsumerCloseAndReconnectTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueDuplicatesTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueMemoryFullMultiBrokersTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueRedeliverTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueRepeaterTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ReliableReconnectTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyNoAdvisoryNetworkTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyTempDestRemovalAdvisoryRaceTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyToTopicViaThreeNetworkHopsTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SingleBrokerVirtualDestinationsWithWildcardLevelDBTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SingleBrokerVirtualDestinationsWithWildcardTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StartAndStopBrokerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StartAndStopClientAndBrokerDoesNotLeaveThreadsRunningTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StaticNetworkTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SubscribeClosePublishThenConsumeTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TempTopicProducerFlowControlTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TestBrokerConnectionDuplexExcludedDestinations.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TestSupport.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerQueueNetworkTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerQueueNetworkUsingTcpTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerStompTemporaryQueueTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTempDestDemandSubscriptionCleanupTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTempQueueNetworkTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTopicNetworkTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTopicNetworkUsingTcpTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerVirtualTopicNetworkLevelDBTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerVirtualTopicNetworkTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicDurableConnectStatsTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicProducerFlowControlTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicRedeliverTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicReplicationTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicSubscriptionSlowConsumerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicSubscriptionZeroPrefetchTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransactionRollbackOrderTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransactionTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransientQueueRedeliverTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerMessageNotSentToRemoteWhenNoConsumerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerMulticastQueueTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkConnectorWildcardDynamicallyIncludedDestinationTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkConnectorWildcardStaticallyIncludedDestinationTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkLoadBalanceTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerQueueClientsReconnectTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerQueueSendReceiveTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTempQueueAdvisoryTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveLotsOfMessagesUsingTcpTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveUsingJavaConfigurationTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveUsingTcpTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerVirtualDestDinamicallyIncludedDestTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerVirtualTopicForwardingTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoMulticastDiscoveryBrokerTopicSendReceiveTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoSecureBrokerRequestReplyTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/UnlimitedEnqueueTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/VerifyNetworkConsumersDisconnectTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/VirtualTopicNetworkClusterReactivationTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/activemq.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker1.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker1A.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker1B.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker2.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker2A.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker2B.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker3A.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker3B.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/multicast-broker-1.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/multicast-broker-2.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/multicast-broker-auto.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rebalance-broker1.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rebalance-broker2.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rebalance-broker3.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-activecluster.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-discovery.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-duplex.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-http.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-secured.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-zeroconf.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/replication-broker1.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/replication-broker2.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/replication-broker3.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/replication-broker4.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rerouting-activemq-A.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rerouting-activemq-B.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rerouting-activemq-C.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rerouting-activemq-D.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-activecluster.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-discovery.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-duplex.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-http.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-secured.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-zeroconf.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/LinkedNodeTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/LockFileTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/ReflectionSupportTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/plugin-broker.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/ConnectorXBeanConfigTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/JDBCPersistenceAdapterXBeanConfigTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/JDBCPersistenceXBeanConfigTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/ManagementContextXBeanConfigTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithEmbeddedBrokerAndPersistenceTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithEmbeddedBrokerTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithSpringFactoryBeanTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithSpringXBeanFactoryBeanTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithXBeanFactoryBeanTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanConfigTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanStartFalseTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanXmlTest.java delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/activemq-policy.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/activemq.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/activemq2.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/connector-test.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/jdbc-persistence-adapter-test.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/jdbc-persistence-test.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/management-context-test.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/spring.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/spring2.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/spring-embedded-xbean-bean-ref.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/spring-embedded-xbean-local.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/spring-embedded-xbean-noversion.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/spring-embedded-xbean.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/spring-embedded.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/spring-jndi.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/spring-queue.xml delete mode 100644 tests/activemq5-unit-tests/src/test/java/spring.xml delete mode 100644 tests/activemq5-unit-tests/src/test/resources/activemq-partition.xml delete mode 100644 tests/activemq5-unit-tests/src/test/resources/activemq.xml delete mode 100644 tests/activemq5-unit-tests/src/test/resources/spring-embedded-xbean-bean-ref.xml delete mode 100644 tests/activemq5-unit-tests/src/test/resources/spring-embedded-xbean-local.xml delete mode 100644 tests/activemq5-unit-tests/src/test/resources/spring-embedded-xbean-noversion.xml delete mode 100644 tests/activemq5-unit-tests/src/test/resources/spring-embedded-xbean.xml delete mode 100644 tests/activemq5-unit-tests/src/test/resources/spring-embedded.xml delete mode 100644 tests/activemq5-unit-tests/src/test/resources/spring-jndi.xml delete mode 100644 tests/activemq5-unit-tests/src/test/resources/spring-queue.xml delete mode 100644 tests/activemq5-unit-tests/src/test/resources/spring-start-false.xml delete mode 100644 tests/activemq5-unit-tests/src/test/resources/spring.xml diff --git a/tests/activemq5-unit-tests/pom.xml b/tests/activemq5-unit-tests/pom.xml index b96c3c878b..b396c7d908 100644 --- a/tests/activemq5-unit-tests/pom.xml +++ b/tests/activemq5-unit-tests/pom.xml @@ -29,16 +29,6 @@ ${project.basedir}/../.. - 3.4.1 - 1.0.6 - 2.5.1 - 5.3.18 - 10.11.1.1 - 3.3 - 3.18 - 1.3 - 1.9.3 - 3.1.4 @@ -93,18 +83,6 @@ ${activemq5-version} - - org.apache.activemq - activemq-leveldb-store - ${activemq5-version} - - - commons-beanutils - commons-beanutils-core - - - - org.apache.activemq activemq-pool @@ -117,36 +95,12 @@ ${activemq5-version} - - org.apache.activemq - activemq-partition - ${activemq5-version} - - - log4j - log4j - - - - org.apache.activemq activemq-stomp ${activemq5-version} - - org.apache.activemq - activemq-console - ${activemq5-version} - - - - org.apache.activemq - activeio-core - ${activeio-core-version} - - junit junit @@ -159,137 +113,23 @@ 4.3.1 - - javax.jmdns - jmdns - ${jmdns-version} - - - - org.apache.ftpserver - ftpserver-core - ${ftpserver-version} - test - - - - org.jmock - jmock-junit4 - ${jmock-version} - test - - - - org.jmock - jmock-legacy - ${jmock-version} - test - - - - org.springframework - spring-jms - ${spring-version} - test - - org.apache.derby derby - ${org-apache-derby-version} - test - - - - commons-io - commons-io - test - - - - commons-net - commons-net - ${commons-net-version} - - - - org.apache.xbean - xbean-spring - ${xbean-version} - test - - - - org.hamcrest - hamcrest-all - ${hamcrest-version} test org.springframework spring-context - ${spring-version} + ${spring.version} test org.springframework spring-test - ${spring-version} - test - - - - org.jasypt - jasypt - ${jasypt-version} - - - - org.jasypt - jasypt-spring31 - ${jasypt-version} - true - - - - org.apache.directory.server - apacheds-core-integ - ${directory-version} - test - - - - org.apache.directory.server - apacheds-server-integ - ${directory-version} - test - - - log4j - log4j - - - - - - org.fusesource.joram-jms-tests - joram-jms-tests - 1.0 - test - - - - org.easymock - easymock - 3.2 - test - - - - org.fusesource.mqtt-client - mqtt-client + ${spring.version} test diff --git a/tests/activemq5-unit-tests/src/test/java/activemq-partition.xml b/tests/activemq5-unit-tests/src/test/java/activemq-partition.xml deleted file mode 100644 index 4bb96f22a9..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/activemq-partition.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/activemq.xml b/tests/activemq5-unit-tests/src/test/java/activemq.xml deleted file mode 100644 index eb49ca08d0..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/activemq.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/EmbeddedBrokerTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/EmbeddedBrokerTestSupport.java index 02d6fd652f..e44351be7d 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/EmbeddedBrokerTestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/EmbeddedBrokerTestSupport.java @@ -32,7 +32,6 @@ import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; import org.junit.rules.TemporaryFolder; -import org.springframework.jms.core.JmsTemplate; /** * A useful base class which creates and closes an embedded broker @@ -45,7 +44,6 @@ public abstract class EmbeddedBrokerTestSupport extends CombinationTestSupport { protected ConnectionFactory connectionFactory; protected boolean useTopic; protected ActiveMQDestination destination; - protected JmsTemplate template; protected boolean disableWrapper = false; public TemporaryFolder temporaryFolder; @@ -68,11 +66,6 @@ public abstract class EmbeddedBrokerTestSupport extends CombinationTestSupport { connectionFactory = createConnectionFactory(); destination = createDestination(); - - template = createJmsTemplate(); - template.setDefaultDestination(destination); - template.setPubSubDomain(useTopic); - template.afterPropertiesSet(); } @Override @@ -115,15 +108,6 @@ public abstract class EmbeddedBrokerTestSupport extends CombinationTestSupport { return "tcp://" + localhostAddress + ":" + (61616 + serverID); } - /** - * Factory method to create a new {@link JmsTemplate} - * - * @return a newly created JmsTemplate - */ - protected JmsTemplate createJmsTemplate() { - return new JmsTemplate(connectionFactory); - } - /** * Factory method to create a new {@link Destination} * diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsMultipleBrokersTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsMultipleBrokersTestSupport.java deleted file mode 100644 index 665782f2b4..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/JmsMultipleBrokersTestSupport.java +++ /dev/null @@ -1,668 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.QueueBrowser; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.jms.Topic; -import java.net.URI; -import java.util.ArrayList; -import java.util.Arrays; -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.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.activemq.advisory.ConsumerEvent; -import org.apache.activemq.advisory.ConsumerEventSource; -import org.apache.activemq.advisory.ConsumerListener; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.broker.region.RegionBroker; -import org.apache.activemq.broker.region.TopicRegion; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.command.BrokerInfo; -import org.apache.activemq.network.DiscoveryNetworkConnector; -import org.apache.activemq.network.NetworkBridge; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.util.IdGenerator; -import org.apache.activemq.util.MessageIdList; -import org.apache.activemq.util.Wait; -import org.apache.activemq.xbean.BrokerFactoryBean; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.Resource; - -/** - * Test case support that allows the easy management and connection of several - * brokers. - */ -public class JmsMultipleBrokersTestSupport extends CombinationTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(JmsMultipleBrokersTestSupport.class); - public static final String AUTO_ASSIGN_TRANSPORT = "tcp://localhost:0"; - public static int maxSetupTime = 5000; - - protected Map brokers; - protected Map destinations; - - protected int messageSize = 1; - - protected boolean persistentDelivery = true; - protected boolean verbose; - - protected NetworkConnector bridgeBrokers(String localBrokerName, String remoteBrokerName) throws Exception { - return bridgeBrokers(localBrokerName, remoteBrokerName, false, 1, true); - } - - protected NetworkConnector bridgeBrokers(String localBrokerName, - String remoteBrokerName, - boolean dynamicOnly) throws Exception { - BrokerService localBroker = brokers.get(localBrokerName).broker; - BrokerService remoteBroker = brokers.get(remoteBrokerName).broker; - - return bridgeBrokers(localBroker, remoteBroker, dynamicOnly, 1, true, false); - } - - protected NetworkConnector bridgeBrokers(String localBrokerName, - String remoteBrokerName, - boolean dynamicOnly, - int networkTTL, - boolean conduit) throws Exception { - BrokerService localBroker = brokers.get(localBrokerName).broker; - BrokerService remoteBroker = brokers.get(remoteBrokerName).broker; - - return bridgeBrokers(localBroker, remoteBroker, dynamicOnly, networkTTL, conduit, false); - } - - // Overwrite this method to specify how you want to bridge the two brokers - // By default, bridge them using add network connector of the local broker - // and the first connector of the remote broker - protected NetworkConnector bridgeBrokers(BrokerService localBroker, - BrokerService remoteBroker, - boolean dynamicOnly, - int networkTTL, - boolean conduit, - boolean failover) throws Exception { - List transportConnectors = remoteBroker.getTransportConnectors(); - URI remoteURI; - if (!transportConnectors.isEmpty()) { - remoteURI = transportConnectors.get(0).getConnectUri(); - String uri = "static:(" + remoteURI + ")"; - if (failover) { - uri = "static:(failover:(" + remoteURI + "))"; - } - NetworkConnector connector = new DiscoveryNetworkConnector(new URI(uri)); - connector.setName("to-" + remoteBroker.getBrokerName()); - connector.setDynamicOnly(dynamicOnly); - connector.setNetworkTTL(networkTTL); - connector.setConduitSubscriptions(conduit); - localBroker.addNetworkConnector(connector); - maxSetupTime = 2000; - return connector; - } else { - throw new Exception("Remote broker has no registered connectors."); - } - - } - - // This will interconnect all brokers using multicast - protected void bridgeAllBrokers() throws Exception { - bridgeAllBrokers("default", 1, false, false); - } - - protected void bridgeAllBrokers(String groupName, int ttl, boolean suppressduplicateQueueSubs) throws Exception { - bridgeAllBrokers(groupName, ttl, suppressduplicateQueueSubs, false); - } - - protected void bridgeAllBrokers(String groupName, - int ttl, - boolean suppressduplicateQueueSubs, - boolean decreasePriority) throws Exception { - Collection brokerList = brokers.values(); - for (Iterator i = brokerList.iterator(); i.hasNext(); ) { - BrokerService broker = i.next().broker; - List transportConnectors = broker.getTransportConnectors(); - - if (transportConnectors.isEmpty()) { - broker.addConnector(new URI(AUTO_ASSIGN_TRANSPORT)); - transportConnectors = broker.getTransportConnectors(); - } - - TransportConnector transport = transportConnectors.get(0); - transport.setDiscoveryUri(new URI("multicast://default?group=" + groupName)); - NetworkConnector nc = broker.addNetworkConnector("multicast://default?group=" + groupName); - nc.setNetworkTTL(ttl); - nc.setSuppressDuplicateQueueSubscriptions(suppressduplicateQueueSubs); - nc.setDecreaseNetworkConsumerPriority(decreasePriority); - } - - // Multicasting may take longer to setup - maxSetupTime = 8000; - } - - protected void waitForBridgeFormation(final int min) throws Exception { - for (BrokerItem brokerItem : brokers.values()) { - final BrokerService broker = brokerItem.broker; - waitForBridgeFormation(broker, min, 0); - } - } - - public boolean waitForBridgeFormation(final BrokerService broker, - final int min, - final int bridgeIndex) throws Exception { - return waitForBridgeFormation(broker, min, bridgeIndex, Wait.MAX_WAIT_MILLIS * 2); - } - - public boolean waitForBridgeFormation(final BrokerService broker, - final int min, - final int bridgeIndex, - long wait) throws Exception { - - boolean result = false; - if (!broker.getNetworkConnectors().isEmpty()) { - result = Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - int activeCount = 0; - for (NetworkBridge bridge : broker.getNetworkConnectors().get(bridgeIndex).activeBridges()) { - if (bridge.getRemoteBrokerName() != null) { - LOG.info("found bridge[" + bridge + "] to " + bridge.getRemoteBrokerName() + " on broker :" + broker.getBrokerName()); - activeCount++; - } - } - return activeCount >= min; - } - }, wait); - } - return result; - } - - protected void waitForMinTopicRegionConsumerCount(final String name, final int count) throws Exception { - final BrokerService broker = brokers.get(name).broker; - final TopicRegion topicRegion = (TopicRegion) ((RegionBroker) broker.getRegionBroker()).getTopicRegion(); - assertTrue("found expected consumers in topic region of" + name, Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("topic consumers: " + name + ", " + topicRegion.getSubscriptions().toString()); - return topicRegion.getSubscriptions().size() >= count; - } - })); - } - - /** - * Timed wait for {@link #hasBridge(String, String)}. - * - * @param localBrokerName - the name of the broker on the "local" side of the bridge - * @param remoteBrokerName - the name of the broker on the "remote" side of the bridge - * @param time - the maximum time to wait for the bridge to be established - * @param units - the units for time - * @throws InterruptedException - if the calling thread is interrupted - * @throws TimeoutException - if the bridge is not established within the time limit - * @throws Exception - some other unknown error occurs - * @see #hasBridge(String, String) - */ - protected void waitForBridge(final String localBrokerName, - final String remoteBrokerName, - long time, - TimeUnit units) throws InterruptedException, TimeoutException, Exception { - if (!Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() { - return hasBridge(localBrokerName, remoteBrokerName); - } - }, units.toMillis(time))) { - throw new TimeoutException("Bridge not established from broker " + localBrokerName + " to " + remoteBrokerName + " within " + units.toMillis(time) + " milliseconds."); - } - } - - /** - * Determines whether a bridge has been established between the specified - * brokers.Establishment means that connections have been created and broker - * info has been exchanged. Due to the asynchronous nature of the - * connections, there is still a possibility that the bridge may fail - * shortly after establishment. - * - * @param localBrokerName - the name of the broker on the "local" side of the bridge - * @param remoteBrokerName - the name of the broker on the "remote" side of the bridge - */ - protected boolean hasBridge(String localBrokerName, String remoteBrokerName) { - final BrokerItem fromBroker = brokers.get(localBrokerName); - if (fromBroker == null) { - throw new IllegalArgumentException("Unknown broker: " + localBrokerName); - } - - for (BrokerInfo peerInfo : fromBroker.broker.getRegionBroker().getPeerBrokerInfos()) { - if (peerInfo.getBrokerName().equals(remoteBrokerName)) { - return true; - } - } - return false; - } - - protected void waitForBridgeFormation() throws Exception { - waitForBridgeFormation(1); - } - - protected void startAllBrokers() throws Exception { - Collection brokerList = brokers.values(); - for (Iterator i = brokerList.iterator(); i.hasNext(); ) { - BrokerService broker = i.next().broker; - broker.start(); - broker.waitUntilStarted(); - } - - Thread.sleep(maxSetupTime); - } - - protected BrokerService createBroker(String brokerName) throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName(brokerName); - brokers.put(brokerName, new BrokerItem(broker)); - - return broker; - } - - protected BrokerService createBroker(URI brokerUri) throws Exception { - BrokerService broker = BrokerFactory.createBroker(brokerUri); - configureBroker(broker); - brokers.put(broker.getBrokerName(), new BrokerItem(broker)); - - return broker; - } - - protected void configureBroker(BrokerService broker) { - } - - protected BrokerService createBroker(Resource configFile) throws Exception { - BrokerFactoryBean brokerFactory = new BrokerFactoryBean(configFile); - brokerFactory.afterPropertiesSet(); - - BrokerService broker = brokerFactory.getBroker(); - brokers.put(broker.getBrokerName(), new BrokerItem(broker)); - - return broker; - } - - protected ConnectionFactory getConnectionFactory(String brokerName) throws Exception { - BrokerItem brokerItem = brokers.get(brokerName); - if (brokerItem != null) { - return brokerItem.factory; - } - return null; - } - - protected Connection createConnection(String brokerName) throws Exception { - BrokerItem brokerItem = brokers.get(brokerName); - if (brokerItem != null) { - return brokerItem.createConnection(); - } - return null; - } - - protected MessageConsumer createSyncConsumer(String brokerName, Destination dest) throws Exception { - BrokerItem brokerItem = brokers.get(brokerName); - if (brokerItem != null) { - Connection con = brokerItem.createConnection(); - con.start(); - Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = sess.createConsumer(dest); - return consumer; - } - return null; - } - - protected MessageConsumer createConsumer(String brokerName, Destination dest) throws Exception { - return createConsumer(brokerName, dest, null, null); - } - - protected MessageConsumer createConsumer(String brokerName, - Destination dest, - String messageSelector) throws Exception { - return createConsumer(brokerName, dest, null, messageSelector); - } - - protected MessageConsumer createConsumer(String brokerName, - Destination dest, - CountDownLatch latch) throws Exception { - return createConsumer(brokerName, dest, latch, null); - } - - protected MessageConsumer createConsumer(String brokerName, - Destination dest, - CountDownLatch latch, - String messageSelector) throws Exception { - BrokerItem brokerItem = brokers.get(brokerName); - if (brokerItem != null) { - return brokerItem.createConsumer(dest, latch, messageSelector); - } - return null; - } - - protected QueueBrowser createBrowser(String brokerName, Destination dest) throws Exception { - BrokerItem brokerItem = brokers.get(brokerName); - if (brokerItem != null) { - return brokerItem.createBrowser(dest); - } - return null; - } - - protected MessageConsumer createDurableSubscriber(String brokerName, Topic dest, String name) throws Exception { - BrokerItem brokerItem = brokers.get(brokerName); - if (brokerItem != null) { - return brokerItem.createDurableSubscriber(dest, name); - } - return null; - } - - protected MessageIdList getBrokerMessages(String brokerName) { - BrokerItem brokerItem = brokers.get(brokerName); - if (brokerItem != null) { - return brokerItem.getAllMessages(); - } - return null; - } - - protected MessageIdList getConsumerMessages(String brokerName, MessageConsumer consumer) { - BrokerItem brokerItem = brokers.get(brokerName); - if (brokerItem != null) { - return brokerItem.getConsumerMessages(consumer); - } - return null; - } - - protected void assertConsumersConnect(String brokerName, - Destination destination, - final int count, - long timeout) throws Exception { - BrokerItem brokerItem = brokers.get(brokerName); - Connection conn = brokerItem.createConnection(); - conn.start(); - ConsumerEventSource ces = new ConsumerEventSource(conn, destination); - - try { - final AtomicInteger actualConnected = new AtomicInteger(); - final CountDownLatch latch = new CountDownLatch(1); - ces.setConsumerListener(new ConsumerListener() { - @Override - public void onConsumerEvent(ConsumerEvent event) { - if (actualConnected.get() < count) { - actualConnected.set(event.getConsumerCount()); - } - if (event.getConsumerCount() >= count) { - latch.countDown(); - } - } - }); - ces.start(); - - latch.await(timeout, TimeUnit.MILLISECONDS); - assertTrue("Expected at least " + count + " consumers to connect, but only " + actualConnected.get() + " connectect within " + timeout + " ms", actualConnected.get() >= count); - - } finally { - ces.stop(); - conn.close(); - brokerItem.connections.remove(conn); - } - } - - protected void sendMessages(String brokerName, Destination destination, int count) throws Exception { - sendMessages(brokerName, destination, count, null); - } - - protected void sendMessages(String brokerName, - Destination destination, - int count, - HashMap properties) throws Exception { - BrokerItem brokerItem = brokers.get(brokerName); - - Connection conn = brokerItem.createConnection(); - conn.start(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageProducer producer = brokerItem.createProducer(destination, sess); - producer.setDeliveryMode(persistentDelivery ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); - - for (int i = 0; i < count; i++) { - TextMessage msg = createTextMessage(sess, conn.getClientID() + ": Message-" + i); - if (properties != null) { - for (String propertyName : properties.keySet()) { - msg.setObjectProperty(propertyName, properties.get(propertyName)); - } - } - producer.send(msg); - onSend(i, msg); - } - - producer.close(); - sess.close(); - conn.close(); - brokerItem.connections.remove(conn); - } - - protected void onSend(int i, TextMessage msg) { - } - - protected TextMessage createTextMessage(Session session, String initText) throws Exception { - TextMessage msg = session.createTextMessage(); - - // Pad message text - if (initText.length() < messageSize) { - char[] data = new char[messageSize - initText.length()]; - Arrays.fill(data, '*'); - String str = new String(data); - msg.setText(initText + str); - - // Do not pad message text - } else { - msg.setText(initText); - } - - return msg; - } - - protected ActiveMQDestination createDestination(String name, boolean topic) throws JMSException { - Destination dest; - if (topic) { - dest = new ActiveMQTopic(name); - destinations.put(name, dest); - return (ActiveMQDestination) dest; - } else { - dest = new ActiveMQQueue(name); - destinations.put(name, dest); - return (ActiveMQDestination) dest; - } - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - brokers = new HashMap<>(); - destinations = new HashMap<>(); - } - - @Override - protected void tearDown() throws Exception { - destroyAllBrokers(); - super.tearDown(); - } - - protected void destroyBroker(String brokerName) throws Exception { - BrokerItem brokerItem = brokers.remove(brokerName); - - if (brokerItem != null) { - brokerItem.destroy(); - } - } - - protected void destroyAllBrokers() throws Exception { - for (Iterator i = brokers.values().iterator(); i.hasNext(); ) { - BrokerItem brokerItem = i.next(); - brokerItem.destroy(); - } - brokers.clear(); - } - - // Class to group broker components together - public class BrokerItem { - - public BrokerService broker; - public ActiveMQConnectionFactory factory; - public List connections; - public Map consumers; - public MessageIdList allMessages = new MessageIdList(); - public boolean persistent; - private IdGenerator id; - - public BrokerItem(BrokerService broker) throws Exception { - this.broker = broker; - - factory = new ActiveMQConnectionFactory(broker.getVmConnectorURI()); - factory.setConnectionIDPrefix(broker.getBrokerName()); - consumers = Collections.synchronizedMap(new HashMap()); - connections = Collections.synchronizedList(new ArrayList()); - allMessages.setVerbose(verbose); - id = new IdGenerator(broker.getBrokerName() + ":"); - } - - public Connection createConnection() throws Exception { - Connection conn = factory.createConnection(); - conn.setClientID(id.generateId()); - - connections.add(conn); - return conn; - } - - public MessageConsumer createConsumer(Destination dest) throws Exception { - return createConsumer(dest, null, null); - } - - public MessageConsumer createConsumer(Destination dest, String messageSelector) throws Exception { - return createConsumer(dest, null, messageSelector); - } - - public MessageConsumer createConsumer(Destination dest, - CountDownLatch latch, - String messageSelector) throws Exception { - Connection c = createConnection(); - c.start(); - Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); - return createConsumerWithSession(dest, s, latch, messageSelector); - } - - public MessageConsumer createConsumerWithSession(Destination dest, Session sess) throws Exception { - return createConsumerWithSession(dest, sess, null, null); - } - - public MessageConsumer createConsumerWithSession(Destination dest, - Session sess, - CountDownLatch latch, - String messageSelector) throws Exception { - MessageConsumer client = sess.createConsumer(dest, messageSelector); - MessageIdList messageIdList = new MessageIdList(); - messageIdList.setCountDownLatch(latch); - messageIdList.setParent(allMessages); - client.setMessageListener(messageIdList); - consumers.put(client, messageIdList); - return client; - } - - public QueueBrowser createBrowser(Destination dest) throws Exception { - Connection c = createConnection(); - c.start(); - Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); - return s.createBrowser((Queue) dest); - } - - public MessageConsumer createDurableSubscriber(Topic dest, String name) throws Exception { - Connection c = createConnection(); - c.start(); - Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); - return createDurableSubscriber(dest, s, name); - } - - public MessageConsumer createDurableSubscriber(Topic dest, Session sess, String name) throws Exception { - MessageConsumer client = sess.createDurableSubscriber(dest, name); - MessageIdList messageIdList = new MessageIdList(); - messageIdList.setParent(allMessages); - client.setMessageListener(messageIdList); - consumers.put(client, messageIdList); - - return client; - } - - public MessageIdList getAllMessages() { - return allMessages; - } - - public MessageIdList getConsumerMessages(MessageConsumer consumer) { - return consumers.get(consumer); - } - - public MessageProducer createProducer(Destination dest) throws Exception { - Connection c = createConnection(); - c.start(); - Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); - return createProducer(dest, s); - } - - public MessageProducer createProducer(Destination dest, Session sess) throws Exception { - MessageProducer client = sess.createProducer(dest); - client.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); - return client; - } - - public void destroy() throws Exception { - while (!connections.isEmpty()) { - Connection c = connections.remove(0); - try { - c.close(); - } catch (ConnectionClosedException e) { - } catch (JMSException e) { - } - } - - broker.stop(); - broker.waitUntilStopped(); - consumers.clear(); - - broker = null; - connections = null; - consumers = null; - factory = null; - } - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/LoadTestBurnIn.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/LoadTestBurnIn.java deleted file mode 100644 index 3a4acfdbf0..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/LoadTestBurnIn.java +++ /dev/null @@ -1,168 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq; - -import javax.jms.BytesMessage; -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.DeliveryMode; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.Topic; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import junit.framework.Test; - -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQDestination; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Small burn test moves sends a moderate amount of messages through the broker, - * to checking to make sure that the broker does not lock up after a while of - * sustained messaging. - */ -public class LoadTestBurnIn extends JmsTestSupport { - - private static final transient Logger LOG = LoggerFactory.getLogger(LoadTestBurnIn.class); - - public ActiveMQDestination destination; - public int deliveryMode; - public byte destinationType; - public boolean durableConsumer; - public int messageCount = 50000; - public int messageSize = 1024; - - public static Test suite() { - return suite(LoadTestBurnIn.class); - } - - @Override - protected void setUp() throws Exception { - LOG.info("Start: " + getName()); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - try { - super.tearDown(); - } catch (Throwable e) { - e.printStackTrace(System.out); - } finally { - LOG.info("End: " + getName()); - } - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - @Override - protected BrokerService createBroker() throws Exception { - return BrokerFactory.createBroker(new URI("broker://(tcp://localhost:0)?useJmx=true")); - // return BrokerFactory.createBroker(new - // URI("xbean:org/apache/activemq/broker/store/loadtester.xml")); - } - - @Override - protected ConnectionFactory createConnectionFactory() throws URISyntaxException, IOException { - return new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getServer().getConnectURI()); - } - - public void initCombosForTestSendReceive() { - addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); - addCombinationValues("durableConsumer", new Object[]{Boolean.TRUE}); - addCombinationValues("messageSize", new Object[]{Integer.valueOf(101), Integer.valueOf(102), Integer.valueOf(103), Integer.valueOf(104), Integer.valueOf(105), Integer.valueOf(106), Integer.valueOf(107), Integer.valueOf(108)}); - } - - public void testSendReceive() throws Exception { - - // Durable consumer combination is only valid with topics - if (durableConsumer && destinationType != ActiveMQDestination.TOPIC_TYPE) { - return; - } - - connection.setClientID(getName()); - connection.getPrefetchPolicy().setAll(1000); - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = createDestination(session, destinationType); - MessageConsumer consumer; - if (durableConsumer) { - consumer = session.createDurableSubscriber((Topic) destination, "sub1:" + System.currentTimeMillis()); - } else { - consumer = session.createConsumer(destination); - } - profilerPause("Ready: "); - - final CountDownLatch producerDoneLatch = new CountDownLatch(1); - - // Send the messages, async - new Thread() { - @Override - public void run() { - Connection connection2 = null; - try { - connection2 = factory.createConnection(); - Session session = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(deliveryMode); - for (int i = 0; i < messageCount; i++) { - BytesMessage m = session.createBytesMessage(); - m.writeBytes(new byte[messageSize]); - producer.send(m); - } - producer.close(); - } catch (JMSException e) { - e.printStackTrace(); - } finally { - safeClose(connection2); - producerDoneLatch.countDown(); - } - - } - }.start(); - - // Make sure all the messages were delivered. - Message message = null; - for (int i = 0; i < messageCount; i++) { - message = consumer.receive(5000); - assertNotNull("Did not get message: " + i, message); - } - - profilerPause("Done: "); - - assertNull(consumer.receiveNoWait()); - message.acknowledge(); - - // Make sure the producer thread finishes. - assertTrue(producerDoneLatch.await(5, TimeUnit.SECONDS)); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/SpringTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/SpringTestSupport.java deleted file mode 100644 index 67ec96c8a3..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/SpringTestSupport.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -import junit.framework.TestCase; - -import org.springframework.context.support.AbstractApplicationContext; - -/** - * A useful base class for spring based unit test cases - */ -public abstract class SpringTestSupport extends TestCase { - - protected AbstractApplicationContext context; - - @Override - protected void setUp() throws Exception { - context = createApplicationContext(); - } - - protected abstract AbstractApplicationContext createApplicationContext(); - - @Override - protected void tearDown() throws Exception { - if (context != null) { - context.destroy(); - } - } - - protected Object getBean(String name) { - Object bean = context.getBean(name); - if (bean == null) { - fail("Should have found bean named '" + name + "' in the Spring ApplicationContext"); - } - return bean; - } - - protected void assertSetEquals(String description, Object[] expected, Set actual) { - Set expectedSet = new HashSet<>(); - expectedSet.addAll(Arrays.asList(expected)); - assertEquals(description, expectedSet, actual); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/TestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/TestSupport.java index 2c55c8f788..9ecb4b7042 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/TestSupport.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/TestSupport.java @@ -35,7 +35,6 @@ import org.apache.activemq.command.ActiveMQTopic; import org.apache.activemq.store.PersistenceAdapter; import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.store.leveldb.LevelDBPersistenceAdapter; import org.apache.activemq.store.memory.MemoryPersistenceAdapter; /** @@ -168,7 +167,7 @@ public abstract class TestSupport extends CombinationTestSupport { return destination.isQueue() ? regionBroker.getQueueRegion().getDestinationMap() : regionBroker.getTopicRegion().getDestinationMap(); } - public static enum PersistenceAdapterChoice {LevelDB, KahaDB, AMQ, JDBC, MEM} + public static enum PersistenceAdapterChoice {KahaDB, AMQ, JDBC, MEM} public PersistenceAdapter setDefaultPersistenceAdapter(BrokerService broker) throws IOException { return setPersistenceAdapter(broker, defaultPersistenceAdapter); @@ -186,9 +185,6 @@ public abstract class TestSupport extends CombinationTestSupport { case KahaDB: adapter = new KahaDBPersistenceAdapter(); break; - case LevelDB: - adapter = new LevelDBPersistenceAdapter(); - break; case MEM: adapter = new MemoryPersistenceAdapter(); break; diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ZeroPrefetchConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ZeroPrefetchConsumerTest.java index 386de2e583..3248459669 100644 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ZeroPrefetchConsumerTest.java +++ b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ZeroPrefetchConsumerTest.java @@ -35,7 +35,6 @@ import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ConsumerControl; import org.apache.activemq.command.ExceptionResponse; -import org.apache.activemq.spring.SpringConsumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -54,9 +53,8 @@ public class ZeroPrefetchConsumerTest extends EmbeddedBrokerTestSupport { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(queue); - MessageListener listener = new SpringConsumer(); try { - consumer.setMessageListener(listener); + consumer.setMessageListener(msg -> {}); fail("Should have thrown JMSException as we cannot use MessageListener with zero prefetch"); } catch (JMSException e) { LOG.info("Received expected exception : " + e); diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/AdvisoryTempDestinationTests.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/AdvisoryTempDestinationTests.java deleted file mode 100644 index 4f6c066eeb..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/AdvisoryTempDestinationTests.java +++ /dev/null @@ -1,226 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.advisory; - -import javax.jms.BytesMessage; -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; -import javax.jms.TemporaryQueue; -import javax.jms.Topic; -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.ConstantPendingMessageLimitStrategy; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQMessage; - -public class AdvisoryTempDestinationTests extends TestCase { - - protected static final int MESSAGE_COUNT = 2000; - protected BrokerService broker; - protected Connection connection; - protected String bindAddress = ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL; - protected int topicCount; - - public void testNoSlowConsumerAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TemporaryQueue queue = s.createTemporaryQueue(); - MessageConsumer consumer = s.createConsumer(queue); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - } - }); - Topic advisoryTopic = AdvisorySupport.getSlowConsumerAdvisoryTopic((ActiveMQDestination) queue); - s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - // start throwing messages at the consumer - MessageProducer producer = s.createProducer(queue); - for (int i = 0; i < MESSAGE_COUNT; i++) { - BytesMessage m = s.createBytesMessage(); - m.writeBytes(new byte[1024]); - producer.send(m); - } - Message msg = advisoryConsumer.receive(1000); - assertNull(msg); - } - - public void testSlowConsumerAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TemporaryQueue queue = s.createTemporaryQueue(); - MessageConsumer consumer = s.createConsumer(queue); - assertNotNull(consumer); - - Topic advisoryTopic = AdvisorySupport.getSlowConsumerAdvisoryTopic((ActiveMQDestination) queue); - s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - // start throwing messages at the consumer - MessageProducer producer = s.createProducer(queue); - for (int i = 0; i < MESSAGE_COUNT; i++) { - BytesMessage m = s.createBytesMessage(); - m.writeBytes(new byte[1024]); - producer.send(m); - } - Message msg = advisoryConsumer.receive(1000); - assertNotNull(msg); - } - - public void testMessageDeliveryAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TemporaryQueue queue = s.createTemporaryQueue(); - MessageConsumer consumer = s.createConsumer(queue); - assertNotNull(consumer); - - Topic advisoryTopic = AdvisorySupport.getMessageDeliveredAdvisoryTopic((ActiveMQDestination) queue); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - //start throwing messages at the consumer - MessageProducer producer = s.createProducer(queue); - - BytesMessage m = s.createBytesMessage(); - m.writeBytes(new byte[1024]); - producer.send(m); - - Message msg = advisoryConsumer.receive(1000); - assertNotNull(msg); - } - - public void testTempMessageConsumedAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TemporaryQueue queue = s.createTemporaryQueue(); - MessageConsumer consumer = s.createConsumer(queue); - - Topic advisoryTopic = AdvisorySupport.getMessageConsumedAdvisoryTopic((ActiveMQDestination) queue); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - //start throwing messages at the consumer - MessageProducer producer = s.createProducer(queue); - - BytesMessage m = s.createBytesMessage(); - m.writeBytes(new byte[1024]); - producer.send(m); - String id = m.getJMSMessageID(); - Message msg = consumer.receive(1000); - assertNotNull(msg); - - msg = advisoryConsumer.receive(1000); - assertNotNull(msg); - - ActiveMQMessage message = (ActiveMQMessage) msg; - ActiveMQMessage payload = (ActiveMQMessage) message.getDataStructure(); - String originalId = payload.getJMSMessageID(); - assertEquals(originalId, id); - } - - public void testMessageExpiredAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = s.createQueue(getClass().getName()); - MessageConsumer consumer = s.createConsumer(queue); - assertNotNull(consumer); - - Topic advisoryTopic = AdvisorySupport.getExpiredMessageTopic((ActiveMQDestination) queue); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - //start throwing messages at the consumer - MessageProducer producer = s.createProducer(queue); - producer.setTimeToLive(1); - for (int i = 0; i < MESSAGE_COUNT; i++) { - BytesMessage m = s.createBytesMessage(); - m.writeBytes(new byte[1024]); - producer.send(m); - } - - Message msg = advisoryConsumer.receive(5000); - assertNotNull(msg); - } - - @Override - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(); - } - ConnectionFactory factory = createConnectionFactory(); - connection = factory.createConnection(); - connection.start(); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - connection.close(); - if (broker != null) { - broker.stop(); - } - } - - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL); - return cf; - } - - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - configureBroker(answer); - answer.start(); - return answer; - } - - protected void configureBroker(BrokerService answer) throws Exception { - answer.setPersistent(false); - ConstantPendingMessageLimitStrategy strategy = new ConstantPendingMessageLimitStrategy(); - strategy.setLimit(10); - PolicyEntry tempQueueEntry = createPolicyEntry(strategy); - tempQueueEntry.setTempQueue(true); - PolicyEntry tempTopicEntry = createPolicyEntry(strategy); - tempTopicEntry.setTempTopic(true); - - PolicyMap pMap = new PolicyMap(); - final List policyEntries = new ArrayList<>(); - policyEntries.add(tempQueueEntry); - policyEntries.add(tempTopicEntry); - pMap.setPolicyEntries(policyEntries); - - answer.setDestinationPolicy(pMap); - answer.addConnector(bindAddress); - answer.setDeleteAllMessagesOnStartup(true); - } - - private PolicyEntry createPolicyEntry(ConstantPendingMessageLimitStrategy strategy) { - PolicyEntry policy = new PolicyEntry(); - policy.setAdvisoryForFastProducers(true); - policy.setAdvisoryForConsumed(true); - policy.setAdvisoryForDelivery(true); - policy.setAdvisoryForDiscardingMessages(true); - policy.setAdvisoryForSlowConsumers(true); - policy.setAdvisoryWhenFull(true); - policy.setProducerFlowControl(false); - policy.setPendingMessageLimitStrategy(strategy); - - return policy; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/AdvisoryTests.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/AdvisoryTests.java deleted file mode 100644 index 0dc8b6d173..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/AdvisoryTests.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.activemq.advisory; - -import javax.jms.BytesMessage; -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; -import javax.jms.Topic; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ActiveMQPrefetchPolicy; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.ConstantPendingMessageLimitStrategy; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQMessage; - -/** - * - */ -public class AdvisoryTests extends TestCase { - - protected static final int MESSAGE_COUNT = 2000; - protected BrokerService broker; - protected Connection connection; - protected String bindAddress = ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL; - protected int topicCount; - - public void testNoSlowConsumerAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = s.createQueue(getClass().getName()); - MessageConsumer consumer = s.createConsumer(queue); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - } - }); - Topic advisoryTopic = AdvisorySupport.getSlowConsumerAdvisoryTopic((ActiveMQDestination) queue); - s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - // start throwing messages at the consumer - MessageProducer producer = s.createProducer(queue); - for (int i = 0; i < MESSAGE_COUNT; i++) { - BytesMessage m = s.createBytesMessage(); - m.writeBytes(new byte[1024]); - producer.send(m); - } - Message msg = advisoryConsumer.receive(1000); - assertNull(msg); - } - - public void testSlowConsumerAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = s.createQueue(getClass().getName()); - MessageConsumer consumer = s.createConsumer(queue); - assertNotNull(consumer); - - Topic advisoryTopic = AdvisorySupport.getSlowConsumerAdvisoryTopic((ActiveMQDestination) queue); - s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - // start throwing messages at the consumer - MessageProducer producer = s.createProducer(queue); - for (int i = 0; i < MESSAGE_COUNT; i++) { - BytesMessage m = s.createBytesMessage(); - m.writeBytes(new byte[1024]); - producer.send(m); - } - Message msg = advisoryConsumer.receive(1000); - assertNotNull(msg); - } - - public void testMessageDeliveryAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = s.createQueue(getClass().getName()); - MessageConsumer consumer = s.createConsumer(queue); - assertNotNull(consumer); - - Topic advisoryTopic = AdvisorySupport.getMessageDeliveredAdvisoryTopic((ActiveMQDestination) queue); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - //start throwing messages at the consumer - MessageProducer producer = s.createProducer(queue); - - BytesMessage m = s.createBytesMessage(); - m.writeBytes(new byte[1024]); - producer.send(m); - - Message msg = advisoryConsumer.receive(1000); - assertNotNull(msg); - } - - public void testMessageConsumedAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = s.createQueue(getClass().getName()); - MessageConsumer consumer = s.createConsumer(queue); - - Topic advisoryTopic = AdvisorySupport.getMessageConsumedAdvisoryTopic((ActiveMQDestination) queue); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - //start throwing messages at the consumer - MessageProducer producer = s.createProducer(queue); - - BytesMessage m = s.createBytesMessage(); - m.writeBytes(new byte[1024]); - producer.send(m); - String id = m.getJMSMessageID(); - Message msg = consumer.receive(1000); - assertNotNull(msg); - - msg = advisoryConsumer.receive(1000); - assertNotNull(msg); - - ActiveMQMessage message = (ActiveMQMessage) msg; - ActiveMQMessage payload = (ActiveMQMessage) message.getDataStructure(); - String originalId = payload.getJMSMessageID(); - assertEquals(originalId, id); - } - - public void testMessageExpiredAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = s.createQueue(getClass().getName()); - MessageConsumer consumer = s.createConsumer(queue); - assertNotNull(consumer); - - Topic advisoryTopic = AdvisorySupport.getExpiredMessageTopic((ActiveMQDestination) queue); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - //start throwing messages at the consumer - MessageProducer producer = s.createProducer(queue); - producer.setTimeToLive(1); - for (int i = 0; i < MESSAGE_COUNT; i++) { - BytesMessage m = s.createBytesMessage(); - m.writeBytes(new byte[1024]); - producer.send(m); - } - - Message msg = advisoryConsumer.receive(2000); - assertNotNull(msg); - } - - public void xtestMessageDiscardedAdvisory() throws Exception { - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = s.createTopic(getClass().getName()); - MessageConsumer consumer = s.createConsumer(topic); - assertNotNull(consumer); - - Topic advisoryTopic = AdvisorySupport.getMessageDiscardedAdvisoryTopic((ActiveMQDestination) topic); - MessageConsumer advisoryConsumer = s.createConsumer(advisoryTopic); - //start throwing messages at the consumer - MessageProducer producer = s.createProducer(topic); - int count = (new ActiveMQPrefetchPolicy().getTopicPrefetch() * 2); - for (int i = 0; i < count; i++) { - BytesMessage m = s.createBytesMessage(); - producer.send(m); - } - - Message msg = advisoryConsumer.receive(1000); - assertNotNull(msg); - } - - @Override - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(); - } - ConnectionFactory factory = createConnectionFactory(); - connection = factory.createConnection(); - connection.start(); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - connection.close(); - if (broker != null) { - broker.stop(); - } - } - - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL); - return cf; - } - - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - configureBroker(answer); - answer.start(); - return answer; - } - - protected void configureBroker(BrokerService answer) throws Exception { - answer.setPersistent(false); - PolicyEntry policy = new PolicyEntry(); - policy.setAdvisoryForFastProducers(true); - policy.setAdvisoryForConsumed(true); - policy.setAdvisoryForDelivery(true); - policy.setAdvisoryForDiscardingMessages(true); - policy.setAdvisoryForSlowConsumers(true); - policy.setAdvisoryWhenFull(true); - policy.setProducerFlowControl(false); - ConstantPendingMessageLimitStrategy strategy = new ConstantPendingMessageLimitStrategy(); - strategy.setLimit(10); - policy.setPendingMessageLimitStrategy(strategy); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - - answer.setDestinationPolicy(pMap); - answer.addConnector(bindAddress); - answer.setDeleteAllMessagesOnStartup(true); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/ConsumerListenerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/ConsumerListenerTest.java deleted file mode 100644 index 20ec2d9d63..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/ConsumerListenerTest.java +++ /dev/null @@ -1,156 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.advisory; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.Session; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * - */ -public class ConsumerListenerTest extends EmbeddedBrokerTestSupport implements ConsumerListener { - - private static final Logger LOG = LoggerFactory.getLogger(ConsumerListenerTest.class); - - protected Session consumerSession1; - protected Session consumerSession2; - protected int consumerCounter; - protected ConsumerEventSource consumerEventSource; - protected BlockingQueue eventQueue = new ArrayBlockingQueue<>(1000); - private Connection connection; - - public void testConsumerEvents() throws Exception { - consumerEventSource.start(); - - consumerSession1 = createConsumer(); - assertConsumerEvent(1, true); - - consumerSession2 = createConsumer(); - assertConsumerEvent(2, true); - - consumerSession1.close(); - consumerSession1 = null; - assertConsumerEvent(1, false); - - consumerSession2.close(); - consumerSession2 = null; - assertConsumerEvent(0, false); - } - - public void testListenWhileAlreadyConsumersActive() throws Exception { - consumerSession1 = createConsumer(); - consumerSession2 = createConsumer(); - - consumerEventSource.start(); - assertConsumerEvent(2, true); - assertConsumerEvent(2, true); - - consumerSession1.close(); - consumerSession1 = null; - assertConsumerEvent(1, false); - - consumerSession2.close(); - consumerSession2 = null; - assertConsumerEvent(0, false); - } - - public void testConsumerEventsOnTemporaryDestination() throws Exception { - - Session s = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - Destination dest = useTopic ? s.createTemporaryTopic() : s.createTemporaryQueue(); - consumerEventSource = new ConsumerEventSource(connection, dest); - consumerEventSource.setConsumerListener(this); - consumerEventSource.start(); - MessageConsumer consumer = s.createConsumer(dest); - assertConsumerEvent(1, true); - consumer.close(); - assertConsumerEvent(0, false); - } - - @Override - public void onConsumerEvent(ConsumerEvent event) { - eventQueue.add(event); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - - connection = createConnection(); - connection.start(); - consumerEventSource = new ConsumerEventSource(connection, destination); - consumerEventSource.setConsumerListener(this); - } - - @Override - protected void tearDown() throws Exception { - if (consumerEventSource != null) { - consumerEventSource.stop(); - } - if (consumerSession2 != null) { - consumerSession2.close(); - } - if (consumerSession1 != null) { - consumerSession1.close(); - } - if (connection != null) { - connection.close(); - } - super.tearDown(); - } - - protected void assertConsumerEvent(int count, boolean started) throws InterruptedException { - ConsumerEvent event = waitForConsumerEvent(); - assertEquals("Consumer count", count, event.getConsumerCount()); - assertEquals("started", started, event.isStarted()); - } - - protected Session createConsumer() throws JMSException { - final String consumerText = "Consumer: " + (++consumerCounter); - LOG.info("Creating consumer: " + consumerText + " on destination: " + destination); - - Session answer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = answer.createConsumer(destination); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - LOG.info("Received message by: " + consumerText + " message: " + message); - } - }); - return answer; - } - - protected ConsumerEvent waitForConsumerEvent() throws InterruptedException { - ConsumerEvent answer = eventQueue.poll(100000, TimeUnit.MILLISECONDS); - assertTrue("Should have received a consumer event!", answer != null); - return answer; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/DestinationListenerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/DestinationListenerTest.java deleted file mode 100644 index 5c968f573f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/DestinationListenerTest.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.activemq.advisory; - -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.isIn; - -/** - * - */ -public class DestinationListenerTest extends EmbeddedBrokerTestSupport implements DestinationListener { - - private static final transient Logger LOG = LoggerFactory.getLogger(DestinationListenerTest.class); - protected ActiveMQConnection connection; - protected ActiveMQQueue sampleQueue = new ActiveMQQueue("foo.bar"); - protected ActiveMQTopic sampleTopic = new ActiveMQTopic("cheese"); - protected List newDestinations = new ArrayList<>(); - - public void testDestiationSourceHasInitialDestinations() throws Exception { - Thread.sleep(1000); - - DestinationSource destinationSource = connection.getDestinationSource(); - Set queues = destinationSource.getQueues(); - Set topics = destinationSource.getTopics(); - - LOG.info("Queues: " + queues); - LOG.info("Topics: " + topics); - - assertTrue("The queues should not be empty!", !queues.isEmpty()); - assertTrue("The topics should not be empty!", !topics.isEmpty()); - - assertTrue("queues contains initial queue: " + queues, queues.contains(sampleQueue)); - assertTrue("topics contains initial topic: " + queues, topics.contains(sampleTopic)); - } - - public void testConsumerForcesNotificationOfNewDestination() throws Exception { - // now lets cause a destination to be created - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQQueue newQueue = new ActiveMQQueue("Test.Cheese"); - session.createConsumer(newQueue); - - Thread.sleep(3000); - - assertThat(newQueue, isIn(newDestinations)); - - LOG.info("New destinations are: " + newDestinations); - } - - public void testProducerForcesNotificationOfNewDestination() throws Exception { - // now lets cause a destination to be created - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQQueue newQueue = new ActiveMQQueue("Test.Beer"); - MessageProducer producer = session.createProducer(newQueue); - TextMessage message = session.createTextMessage("world"); - producer.send(message); - - Thread.sleep(3000); - - assertThat(newQueue, isIn(newDestinations)); - - LOG.info("New destinations are: " + newDestinations); - } - - @Override - public void onDestinationEvent(DestinationEvent event) { - ActiveMQDestination destination = event.getDestination(); - if (event.isAddOperation()) { - LOG.info("Added: " + destination); - newDestinations.add(destination); - } else { - LOG.info("Removed: " + destination); - newDestinations.remove(destination); - } - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - - connection = (ActiveMQConnection) createConnection(); - connection.start(); - connection.getDestinationSource().setDestinationListener(this); - } - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - broker.setDestinations(new ActiveMQDestination[]{sampleQueue, sampleTopic}); - return broker; - } - - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - super.tearDown(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/ProducerListenerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/ProducerListenerTest.java deleted file mode 100644 index 720282945e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/ProducerListenerTest.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.activemq.advisory; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * - */ -public class ProducerListenerTest extends EmbeddedBrokerTestSupport implements ProducerListener { - - private static final Logger LOG = LoggerFactory.getLogger(ProducerListenerTest.class); - - protected Session consumerSession1; - protected Session consumerSession2; - protected int consumerCounter; - protected ProducerEventSource producerEventSource; - protected BlockingQueue eventQueue = new ArrayBlockingQueue<>(1000); - private Connection connection; - - public void testProducerEvents() throws Exception { - producerEventSource.start(); - - consumerSession1 = createProducer(); - assertProducerEvent(1, true); - - consumerSession2 = createProducer(); - assertProducerEvent(2, true); - - consumerSession1.close(); - consumerSession1 = null; - assertProducerEvent(1, false); - - consumerSession2.close(); - consumerSession2 = null; - assertProducerEvent(0, false); - } - - public void testListenWhileAlreadyConsumersActive() throws Exception { - consumerSession1 = createProducer(); - consumerSession2 = createProducer(); - - producerEventSource.start(); - assertProducerEvent(2, true); - assertProducerEvent(2, true); - - consumerSession1.close(); - consumerSession1 = null; - assertProducerEvent(1, false); - - consumerSession2.close(); - consumerSession2 = null; - assertProducerEvent(0, false); - } - - public void testConsumerEventsOnTemporaryDestination() throws Exception { - - Session s = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - Destination dest = useTopic ? s.createTemporaryTopic() : s.createTemporaryQueue(); - producerEventSource = new ProducerEventSource(connection, dest); - producerEventSource.setProducerListener(this); - producerEventSource.start(); - MessageProducer producer = s.createProducer(dest); - assertProducerEvent(1, true); - producer.close(); - assertProducerEvent(0, false); - } - - @Override - public void onProducerEvent(ProducerEvent event) { - eventQueue.add(event); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - - connection = createConnection(); - connection.start(); - producerEventSource = new ProducerEventSource(connection, destination); - producerEventSource.setProducerListener(this); - } - - @Override - protected void tearDown() throws Exception { - if (producerEventSource != null) { - producerEventSource.stop(); - } - if (consumerSession2 != null) { - consumerSession2.close(); - } - if (consumerSession1 != null) { - consumerSession1.close(); - } - if (connection != null) { - connection.close(); - } - super.tearDown(); - } - - protected void assertProducerEvent(int count, boolean started) throws InterruptedException { - ProducerEvent event = waitForProducerEvent(); - assertEquals("Producer count", count, event.getProducerCount()); - assertEquals("started", started, event.isStarted()); - } - - protected Session createProducer() throws JMSException { - final String consumerText = "Consumer: " + (++consumerCounter); - LOG.info("Creating consumer: " + consumerText + " on destination: " + destination); - - Session answer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = answer.createProducer(destination); - assertNotNull(producer); - - return answer; - } - - protected ProducerEvent waitForProducerEvent() throws InterruptedException { - ProducerEvent answer = eventQueue.poll(100000, TimeUnit.MILLISECONDS); - assertTrue("Should have received a consumer event!", answer != null); - return answer; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempDestDeleteTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempDestDeleteTest.java deleted file mode 100644 index b10f3cb0bd..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempDestDeleteTest.java +++ /dev/null @@ -1,152 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.advisory; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.Session; -import javax.jms.Topic; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.broker.region.RegionBroker; -import org.apache.activemq.command.ActiveMQTempQueue; -import org.apache.activemq.command.ActiveMQTempTopic; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class TempDestDeleteTest extends EmbeddedBrokerTestSupport implements ConsumerListener { - - private static final Logger LOG = LoggerFactory.getLogger(TempDestDeleteTest.class); - - protected int consumerCounter; - protected ConsumerEventSource topicConsumerEventSource; - protected BlockingQueue eventQueue = new ArrayBlockingQueue<>(1000); - - private ConsumerEventSource queueConsumerEventSource; - private Connection connection; - private Session session; - private ActiveMQTempTopic tempTopic; - private ActiveMQTempQueue tempQueue; - - public void testDeleteTempTopicDeletesAvisoryTopics() throws Exception { - topicConsumerEventSource.start(); - - MessageConsumer consumer = createConsumer(tempTopic); - assertConsumerEvent(1, true); - - Topic advisoryTopic = AdvisorySupport.getConsumerAdvisoryTopic(tempTopic); - assertTrue(destinationExists(advisoryTopic)); - - consumer.close(); - - // Once we delete the topic, the advisory topic for the destination - // should also be deleted. - tempTopic.delete(); - - assertFalse(destinationExists(advisoryTopic)); - } - - public void testDeleteTempQueueDeletesAvisoryTopics() throws Exception { - queueConsumerEventSource.start(); - - MessageConsumer consumer = createConsumer(tempQueue); - assertConsumerEvent(1, true); - - Topic advisoryTopic = AdvisorySupport.getConsumerAdvisoryTopic(tempQueue); - assertTrue(destinationExists(advisoryTopic)); - - consumer.close(); - - // Once we delete the queue, the advisory topic for the destination - // should also be deleted. - tempQueue.delete(); - - assertFalse(destinationExists(advisoryTopic)); - } - - private boolean destinationExists(Destination dest) throws Exception { - RegionBroker rb = (RegionBroker) broker.getBroker().getAdaptor(RegionBroker.class); - return rb.getTopicRegion().getDestinationMap().containsKey(dest) || rb.getQueueRegion().getDestinationMap().containsKey(dest) || rb.getTempTopicRegion().getDestinationMap().containsKey(dest) || rb.getTempQueueRegion().getDestinationMap().containsKey(dest); - } - - @Override - public void onConsumerEvent(ConsumerEvent event) { - eventQueue.add(event); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - connection = createConnection(); - connection.start(); - - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - tempTopic = (ActiveMQTempTopic) session.createTemporaryTopic(); - topicConsumerEventSource = new ConsumerEventSource(connection, tempTopic); - topicConsumerEventSource.setConsumerListener(this); - - tempQueue = (ActiveMQTempQueue) session.createTemporaryQueue(); - queueConsumerEventSource = new ConsumerEventSource(connection, tempQueue); - queueConsumerEventSource.setConsumerListener(this); - } - - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - super.tearDown(); - } - - protected void assertConsumerEvent(int count, boolean started) throws InterruptedException { - ConsumerEvent event = waitForConsumerEvent(); - assertEquals("Consumer count", count, event.getConsumerCount()); - assertEquals("started", started, event.isStarted()); - } - - protected MessageConsumer createConsumer(Destination dest) throws JMSException { - final String consumerText = "Consumer: " + (++consumerCounter); - LOG.info("Creating consumer: " + consumerText + " on destination: " + dest); - - MessageConsumer consumer = session.createConsumer(dest); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - LOG.info("Received message by: " + consumerText + " message: " + message); - } - }); - return consumer; - } - - protected ConsumerEvent waitForConsumerEvent() throws InterruptedException { - ConsumerEvent answer = eventQueue.poll(1000, TimeUnit.MILLISECONDS); - assertTrue("Should have received a consumer event!", answer != null); - return answer; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempDestLoadTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempDestLoadTest.java deleted file mode 100644 index f3ead0bcca..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempDestLoadTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.advisory; - -import javax.jms.Connection; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TemporaryQueue; -import javax.jms.TemporaryTopic; - -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.broker.region.Destination; -import org.apache.activemq.broker.region.RegionBroker; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class TempDestLoadTest extends EmbeddedBrokerTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(TempDestLoadTest.class); - - protected int consumerCounter; - private Connection connection; - private Session session; - private static final int MESSAGE_COUNT = 2000; - - public void testLoadTempAdvisoryQueues() throws Exception { - - for (int i = 0; i < MESSAGE_COUNT; i++) { - TemporaryQueue tempQueue = session.createTemporaryQueue(); - MessageConsumer consumer = session.createConsumer(tempQueue); - MessageProducer producer = session.createProducer(tempQueue); - consumer.close(); - producer.close(); - tempQueue.delete(); - } - - AdvisoryBroker ab = (AdvisoryBroker) broker.getBroker().getAdaptor(AdvisoryBroker.class); - - assertTrue(ab.getAdvisoryDestinations().size() == 0); - assertTrue(ab.getAdvisoryConsumers().size() == 0); - assertTrue(ab.getAdvisoryProducers().size() == 0); - - RegionBroker rb = (RegionBroker) broker.getBroker().getAdaptor(RegionBroker.class); - - for (Destination dest : rb.getDestinationMap().values()) { - LOG.debug("Destination: {}", dest); - } - - // there should be at least 2 destinations - advisories - - // 1 for the connection + 1 generic ones - assertTrue("Should be at least 2 destinations", rb.getDestinationMap().size() > 2); - } - - public void testLoadTempAdvisoryTopics() throws Exception { - for (int i = 0; i < MESSAGE_COUNT; i++) { - TemporaryTopic tempTopic = session.createTemporaryTopic(); - MessageConsumer consumer = session.createConsumer(tempTopic); - MessageProducer producer = session.createProducer(tempTopic); - consumer.close(); - producer.close(); - tempTopic.delete(); - } - - AdvisoryBroker ab = (AdvisoryBroker) broker.getBroker().getAdaptor(AdvisoryBroker.class); - assertTrue(ab.getAdvisoryDestinations().size() == 0); - assertTrue(ab.getAdvisoryConsumers().size() == 0); - assertTrue(ab.getAdvisoryProducers().size() == 0); - RegionBroker rb = (RegionBroker) broker.getBroker().getAdaptor(RegionBroker.class); - - for (Destination dest : rb.getDestinationMap().values()) { - LOG.debug("Destination: {}", dest); - } - - // there should be at least 2 destinations - advisories - - // 1 for the connection + 1 generic ones - assertTrue("Should be at least 2 destinations", rb.getDestinationMap().size() > 2); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - connection = createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } - - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - super.tearDown(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempQueueMemoryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempQueueMemoryTest.java deleted file mode 100644 index 2b93b8b58d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/advisory/TempQueueMemoryTest.java +++ /dev/null @@ -1,170 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.advisory; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TemporaryQueue; -import java.util.Vector; - -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.broker.region.RegionBroker; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; - -public class TempQueueMemoryTest extends EmbeddedBrokerTestSupport { - - protected Connection serverConnection; - protected Session serverSession; - protected Connection clientConnection; - protected Session clientSession; - protected Destination serverDestination; - protected int messagesToSend = 10; - protected boolean deleteTempQueue = true; - protected boolean serverTransactional = false; - protected boolean clientTransactional = false; - protected int numConsumers = 1; - protected int numProducers = 1; - - public void testConcurrentProducerRequestReply() throws Exception { - numProducers = 10; - testLoadRequestReply(); - } - - public void testLoadRequestReply() throws Exception { - for (int i = 0; i < numConsumers; i++) { - serverSession.createConsumer(serverDestination).setMessageListener(new MessageListener() { - @Override - public void onMessage(Message msg) { - try { - Destination replyTo = msg.getJMSReplyTo(); - MessageProducer producer = serverSession.createProducer(replyTo); - producer.send(replyTo, msg); - if (serverTransactional) { - serverSession.commit(); - } - producer.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } - - class Producer extends Thread { - - private final int numToSend; - - public Producer(int numToSend) { - this.numToSend = numToSend; - } - - @Override - public void run() { - try { - Session session = clientConnection.createSession(clientTransactional, clientTransactional ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(serverDestination); - - for (int i = 0; i < numToSend; i++) { - TemporaryQueue replyTo = session.createTemporaryQueue(); - MessageConsumer consumer = session.createConsumer(replyTo); - Message msg = session.createMessage(); - msg.setJMSReplyTo(replyTo); - producer.send(msg); - if (clientTransactional) { - session.commit(); - } - consumer.receive(); - if (clientTransactional) { - session.commit(); - } - consumer.close(); - if (deleteTempQueue) { - replyTo.delete(); - } else { - // temp queue will be cleaned up on clientConnection.close - } - } - } catch (JMSException e) { - e.printStackTrace(); - } - } - } - Vector threads = new Vector<>(numProducers); - for (int i = 0; i < numProducers; i++) { - threads.add(new Producer(messagesToSend / numProducers)); - } - startAndJoinThreads(threads); - - clientSession.close(); - serverSession.close(); - clientConnection.close(); - serverConnection.close(); - - AdvisoryBroker ab = (AdvisoryBroker) broker.getBroker().getAdaptor(AdvisoryBroker.class); - - // The server destination will be left - assertTrue(ab.getAdvisoryDestinations().size() == 1); - - assertTrue("should be zero but is " + ab.getAdvisoryConsumers().size(), ab.getAdvisoryConsumers().size() == 0); - assertTrue("should be zero but is " + ab.getAdvisoryProducers().size(), ab.getAdvisoryProducers().size() == 0); - - RegionBroker rb = (RegionBroker) broker.getBroker().getAdaptor(RegionBroker.class); - - assertTrue(rb.getDestinationMap().size() >= 6); - } - - private void startAndJoinThreads(Vector threads) throws Exception { - for (Thread thread : threads) { - thread.start(); - } - for (Thread thread : threads) { - thread.join(); - } - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - serverConnection = createConnection(); - serverConnection.start(); - serverSession = serverConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - clientConnection = createConnection(); - clientConnection.start(); - clientSession = clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - serverDestination = createDestination(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - serverTransactional = clientTransactional = false; - numConsumers = numProducers = 1; - messagesToSend = 2000; - } - - @Override - protected ActiveMQDestination createDestination() { - return new ActiveMQQueue(getClass().getName()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobDownloadStrategyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobDownloadStrategyTest.java deleted file mode 100644 index 87679fae02..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobDownloadStrategyTest.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.activemq.blob; - -import javax.jms.JMSException; -import java.io.File; -import java.io.FileWriter; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; - -import org.apache.activemq.command.ActiveMQBlobMessage; - -public class FTPBlobDownloadStrategyTest extends FTPTestSupport { - - final int FILE_SIZE = Short.MAX_VALUE * 10; - - public void testDownload() throws Exception { - setConnection(); - - // create file - File uploadFile = new File(ftpHomeDirFile, "test.txt"); - FileWriter wrt = new FileWriter(uploadFile); - - wrt.write("hello world"); - - for (int ix = 0; ix < FILE_SIZE; ++ix) { - wrt.write("a"); - } - - wrt.close(); - - ActiveMQBlobMessage message = new ActiveMQBlobMessage(); - BlobDownloadStrategy strategy = new FTPBlobDownloadStrategy(new BlobTransferPolicy()); - InputStream stream; - try { - message.setURL(new URL(ftpUrl + "test.txt")); - stream = strategy.getInputStream(message); - int i = stream.read(); - StringBuilder sb = new StringBuilder(2048); - while (i != -1) { - sb.append((char) i); - i = stream.read(); - } - assertEquals("hello world", sb.toString().substring(0, "hello world".length())); - assertEquals(FILE_SIZE, sb.toString().substring("hello world".length()).length()); - - assertTrue(uploadFile.exists()); - strategy.deleteFile(message); - assertFalse(uploadFile.exists()); - - } catch (Exception e) { - e.printStackTrace(); - assertTrue(false); - } - } - - public void testWrongAuthentification() throws MalformedURLException { - ActiveMQBlobMessage message = new ActiveMQBlobMessage(); - BlobDownloadStrategy strategy = new FTPBlobDownloadStrategy(new BlobTransferPolicy()); - try { - message.setURL(new URL("ftp://" + userNamePass + "_wrong:" + userNamePass + "@localhost:" + ftpPort + "/ftptest/")); - strategy.getInputStream(message); - } catch (JMSException e) { - assertEquals("Wrong Exception", "Cant Authentificate to FTP-Server", e.getMessage()); - return; - } catch (Exception e) { - System.out.println(e); - assertTrue("Wrong Exception " + e, false); - return; - } - - assertTrue("Expect Exception", false); - } - - public void testWrongFTPPort() throws MalformedURLException { - ActiveMQBlobMessage message = new ActiveMQBlobMessage(); - BlobDownloadStrategy strategy = new FTPBlobDownloadStrategy(new BlobTransferPolicy()); - try { - message.setURL(new URL("ftp://" + userNamePass + ":" + userNamePass + "@localhost:" + 422 + "/ftptest/")); - strategy.getInputStream(message); - } catch (JMSException e) { - assertEquals("Wrong Exception", "Problem connecting the FTP-server", e.getMessage()); - return; - } catch (Exception e) { - e.printStackTrace(); - assertTrue("Wrong Exception " + e, false); - return; - } - - assertTrue("Expect Exception", false); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobTest.java deleted file mode 100644 index 20958f14ef..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobTest.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.activemq.blob; - -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.InputStream; - -import org.apache.activemq.ActiveMQSession; -import org.apache.activemq.BlobMessage; -import org.apache.activemq.command.ActiveMQBlobMessage; - -public class FTPBlobTest extends FTPTestSupport { - - public void testBlobFile() throws Exception { - setConnection(); - // first create Message - File file = File.createTempFile("amq-data-file-", ".dat"); - // lets write some data - String content = "hello world " + System.currentTimeMillis(); - BufferedWriter writer = new BufferedWriter(new FileWriter(file)); - writer.append(content); - writer.close(); - - ActiveMQSession session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - MessageConsumer consumer = session.createConsumer(destination); - BlobMessage message = session.createBlobMessage(file); - message.setName("fileName"); - - producer.send(message); - Thread.sleep(1000); - - // check message send - Message msg = consumer.receive(1000); - assertTrue(msg instanceof ActiveMQBlobMessage); - - assertEquals("name is correct", "fileName", ((ActiveMQBlobMessage) msg).getName()); - InputStream input = ((ActiveMQBlobMessage) msg).getInputStream(); - StringBuilder b = new StringBuilder(); - int i = input.read(); - while (i != -1) { - b.append((char) i); - i = input.read(); - } - input.close(); - File uploaded = new File(ftpHomeDirFile, msg.getJMSMessageID().toString().replace(":", "_")); - assertEquals(content, b.toString()); - assertTrue(uploaded.exists()); - ((ActiveMQBlobMessage) msg).deleteFile(); - assertFalse(uploaded.exists()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobUploadStrategyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobUploadStrategyTest.java deleted file mode 100644 index 29306c654e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPBlobUploadStrategyTest.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.activemq.blob; - -import javax.jms.JMSException; -import javax.jms.Session; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQSession; -import org.apache.activemq.command.ActiveMQBlobMessage; - -public class FTPBlobUploadStrategyTest extends FTPTestSupport { - - public void testFileUpload() throws Exception { - setConnection(); - File file = File.createTempFile("amq-data-file-", ".dat"); - // lets write some data - BufferedWriter writer = new BufferedWriter(new FileWriter(file)); - writer.append("hello world"); - writer.close(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ((ActiveMQConnection) connection).setCopyMessageOnSend(false); - - ActiveMQBlobMessage message = (ActiveMQBlobMessage) ((ActiveMQSession) session).createBlobMessage(file); - message.setJMSMessageID("testmessage"); - message.onSend(); - assertEquals(ftpUrl + "ID_testmessage", message.getURL().toString()); - File uploaded = new File(ftpHomeDirFile, "ID_testmessage"); - assertTrue("File doesn't exists", uploaded.exists()); - } - - public void testWriteDenied() throws Exception { - userNamePass = "guest"; - setConnection(); - File file = File.createTempFile("amq-data-file-", ".dat"); - // lets write some data - BufferedWriter writer = new BufferedWriter(new FileWriter(file)); - writer.append("hello world"); - writer.close(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ((ActiveMQConnection) connection).setCopyMessageOnSend(false); - - ActiveMQBlobMessage message = (ActiveMQBlobMessage) ((ActiveMQSession) session).createBlobMessage(file); - message.setJMSMessageID("testmessage"); - try { - message.onSend(); - } catch (JMSException e) { - e.printStackTrace(); - return; - } - fail("Should have failed with permission denied exception!"); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPTestSupport.java deleted file mode 100644 index 84c59a3cdf..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FTPTestSupport.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.activemq.blob; - -import javax.jms.Connection; -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.util.IOHelper; -import org.apache.ftpserver.FtpServer; -import org.apache.ftpserver.FtpServerFactory; -import org.apache.ftpserver.ftplet.Authority; -import org.apache.ftpserver.ftplet.UserManager; -import org.apache.ftpserver.listener.ListenerFactory; -import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory; -import org.apache.ftpserver.usermanager.impl.BaseUser; -import org.apache.ftpserver.usermanager.impl.WritePermission; -import org.jmock.Mockery; - -public abstract class FTPTestSupport extends EmbeddedBrokerTestSupport { - - protected static final String ftpServerListenerName = "default"; - protected Connection connection; - protected FtpServer server; - String userNamePass = "activemq"; - - Mockery context = null; - String ftpUrl; - int ftpPort; - - final File ftpHomeDirFile = new File("target/FTPBlobTest/ftptest"); - - @Override - protected void setUp() throws Exception { - - if (ftpHomeDirFile.getParentFile().exists()) { - IOHelper.deleteFile(ftpHomeDirFile.getParentFile()); - } - ftpHomeDirFile.mkdirs(); - ftpHomeDirFile.getParentFile().deleteOnExit(); - - FtpServerFactory serverFactory = new FtpServerFactory(); - ListenerFactory factory = new ListenerFactory(); - - PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory(); - UserManager userManager = userManagerFactory.createUserManager(); - - BaseUser user = new BaseUser(); - user.setName("activemq"); - user.setPassword("activemq"); - user.setHomeDirectory(ftpHomeDirFile.getParent()); - - // authorize user - List auths = new ArrayList<>(); - Authority auth = new WritePermission(); - auths.add(auth); - user.setAuthorities(auths); - - userManager.save(user); - - BaseUser guest = new BaseUser(); - guest.setName("guest"); - guest.setPassword("guest"); - guest.setHomeDirectory(ftpHomeDirFile.getParent()); - - userManager.save(guest); - - serverFactory.setUserManager(userManager); - factory.setPort(0); - serverFactory.addListener(ftpServerListenerName, factory.createListener()); - server = serverFactory.createServer(); - server.start(); - ftpPort = serverFactory.getListener(ftpServerListenerName).getPort(); - super.setUp(); - } - - public void setConnection() throws Exception { - ftpUrl = "ftp://" + userNamePass + ":" + userNamePass + "@localhost:" + ftpPort + "/ftptest/"; - bindAddress = "vm://localhost?jms.blobTransferPolicy.defaultUploadUrl=" + ftpUrl; - - connectionFactory = createConnectionFactory(); - - connection = createConnection(); - connection.start(); - } - - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.stop(); - } - super.tearDown(); - if (server != null) { - server.stop(); - } - IOHelper.deleteFile(ftpHomeDirFile.getParentFile()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FilesystemBlobTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FilesystemBlobTest.java deleted file mode 100644 index 7f0a769976..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/blob/FilesystemBlobTest.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.activemq.blob; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.InputStream; - -import org.apache.activemq.ActiveMQSession; -import org.apache.activemq.BlobMessage; -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.command.ActiveMQBlobMessage; -import org.apache.activemq.util.IOHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class FilesystemBlobTest extends EmbeddedBrokerTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(FilesystemBlobTest.class); - - private Connection connection; - private final String tmpDir = System.getProperty("user.dir") + "/target/FilesystemBlobTest"; - - @Override - public void setUp() throws Exception { - super.setUp(); - // replace \ with / to let it work on windows too - String fileUrl = "file:///" + tmpDir.replaceAll("\\\\", "/"); - LOG.info("Using file: " + fileUrl); - bindAddress = "vm://localhost?jms.blobTransferPolicy.defaultUploadUrl=" + fileUrl; - - connectionFactory = createConnectionFactory(); - - connection = createConnection(); - connection.start(); - } - - public void testBlobFile() throws Exception { - // first create Message - File file = File.createTempFile("amq-data-file-", ".dat"); - // lets write some data - String content = "hello world " + System.currentTimeMillis(); - BufferedWriter writer = new BufferedWriter(new FileWriter(file)); - writer.append(content); - writer.close(); - - ActiveMQSession session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - MessageConsumer consumer = session.createConsumer(destination); - BlobMessage message = session.createBlobMessage(file); - - producer.send(message); - Thread.sleep(1000); - - // check message send - Message msg = consumer.receive(1000); - assertTrue(msg instanceof ActiveMQBlobMessage); - - InputStream input = ((ActiveMQBlobMessage) msg).getInputStream(); - StringBuilder b = new StringBuilder(); - int i = input.read(); - while (i != -1) { - b.append((char) i); - i = input.read(); - } - input.close(); - File uploaded = new File(tmpDir, msg.getJMSMessageID().toString().replace(":", "_")); - assertEquals(content, b.toString()); - assertTrue(uploaded.exists()); - ((ActiveMQBlobMessage) msg).deleteFile(); - assertFalse(uploaded.exists()); - } - - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.stop(); - } - super.tearDown(); - - IOHelper.deleteFile(new File(tmpDir)); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerRedeliveryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerRedeliveryTest.java deleted file mode 100644 index 8b2692d176..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerRedeliveryTest.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.activemq.broker; - -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.RedeliveryPolicy; -import org.apache.activemq.broker.region.policy.RedeliveryPolicyMap; -import org.apache.activemq.broker.region.policy.SharedDeadLetterStrategy; -import org.apache.activemq.broker.util.RedeliveryPlugin; -import org.apache.activemq.command.ActiveMQQueue; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class BrokerRedeliveryTest extends org.apache.activemq.TestSupport { - - static final Logger LOG = LoggerFactory.getLogger(BrokerRedeliveryTest.class); - BrokerService broker = null; - - final ActiveMQQueue destination = new ActiveMQQueue("Redelivery"); - final String data = "hi"; - final long redeliveryDelayMillis = 2000; - long initialRedeliveryDelayMillis = 4000; - int maxBrokerRedeliveries = 2; - - public void testScheduledRedelivery() throws Exception { - doTestScheduledRedelivery(maxBrokerRedeliveries, true); - } - - public void testInfiniteRedelivery() throws Exception { - initialRedeliveryDelayMillis = redeliveryDelayMillis; - maxBrokerRedeliveries = RedeliveryPolicy.NO_MAXIMUM_REDELIVERIES; - doTestScheduledRedelivery(RedeliveryPolicy.DEFAULT_MAXIMUM_REDELIVERIES + 1, false); - } - - public void doTestScheduledRedelivery(int maxBrokerRedeliveriesToValidate, boolean validateDLQ) throws Exception { - - startBroker(true); - sendMessage(0); - - ActiveMQConnection consumerConnection = (ActiveMQConnection) createConnection(); - RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy(); - redeliveryPolicy.setInitialRedeliveryDelay(0); - redeliveryPolicy.setMaximumRedeliveries(0); - consumerConnection.setRedeliveryPolicy(redeliveryPolicy); - consumerConnection.start(); - Session consumerSession = consumerConnection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer consumer = consumerSession.createConsumer(destination); - Message message = consumer.receive(1000); - assertNotNull("got message", message); - LOG.info("got: " + message); - consumerSession.rollback(); - - for (int i = 0; i < maxBrokerRedeliveriesToValidate; i++) { - Message shouldBeNull = consumer.receive(500); - assertNull("did not get message after redelivery count exceeded: " + shouldBeNull, shouldBeNull); - - TimeUnit.SECONDS.sleep(3); - - Message brokerRedeliveryMessage = consumer.receive(500); - LOG.info("got: " + brokerRedeliveryMessage); - assertNotNull("got message via broker redelivery after delay", brokerRedeliveryMessage); - assertEquals("message matches", message.getStringProperty("data"), brokerRedeliveryMessage.getStringProperty("data")); - assertEquals("has expiryDelay specified", i == 0 ? initialRedeliveryDelayMillis : redeliveryDelayMillis, brokerRedeliveryMessage.getLongProperty(RedeliveryPlugin.REDELIVERY_DELAY)); - - consumerSession.rollback(); - } - - if (validateDLQ) { - MessageConsumer dlqConsumer = consumerSession.createConsumer(new ActiveMQQueue(SharedDeadLetterStrategy.DEFAULT_DEAD_LETTER_QUEUE_NAME)); - Message dlqMessage = dlqConsumer.receive(2000); - assertNotNull("Got message from dql", dlqMessage); - assertEquals("message matches", message.getStringProperty("data"), dlqMessage.getStringProperty("data")); - consumerSession.commit(); - } else { - // consume/commit ok - message = consumer.receive(3000); - assertNotNull("got message", message); - assertEquals("redeliveries accounted for", maxBrokerRedeliveriesToValidate + 2, message.getLongProperty("JMSXDeliveryCount")); - consumerSession.commit(); - } - - consumerConnection.close(); - } - - public void testNoScheduledRedeliveryOfExpired() throws Exception { - startBroker(true); - ActiveMQConnection consumerConnection = (ActiveMQConnection) createConnection(); - consumerConnection.start(); - Session consumerSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = consumerSession.createConsumer(destination); - sendMessage(1500); - Message message = consumer.receive(1000); - assertNotNull("got message", message); - - // ensure there is another consumer to redispatch to - MessageConsumer redeliverConsumer = consumerSession.createConsumer(destination); - - // allow consumed to expire so it gets redelivered - TimeUnit.SECONDS.sleep(2); - consumer.close(); - - // should go to dlq as it has expired - // validate DLQ - MessageConsumer dlqConsumer = consumerSession.createConsumer(new ActiveMQQueue(SharedDeadLetterStrategy.DEFAULT_DEAD_LETTER_QUEUE_NAME)); - Message dlqMessage = dlqConsumer.receive(2000); - assertNotNull("Got message from dql", dlqMessage); - assertEquals("message matches", message.getStringProperty("data"), dlqMessage.getStringProperty("data")); - } - - private void sendMessage(int timeToLive) throws Exception { - ActiveMQConnection producerConnection = (ActiveMQConnection) createConnection(); - producerConnection.start(); - Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = producerSession.createProducer(destination); - if (timeToLive > 0) { - producer.setTimeToLive(timeToLive); - } - Message message = producerSession.createMessage(); - message.setStringProperty("data", data); - producer.send(message); - producerConnection.close(); - } - - private void startBroker(boolean deleteMessages) throws Exception { - broker = new BrokerService(); - broker.setSchedulerSupport(true); - - RedeliveryPlugin redeliveryPlugin = new RedeliveryPlugin(); - - RedeliveryPolicy brokerRedeliveryPolicy = new RedeliveryPolicy(); - brokerRedeliveryPolicy.setRedeliveryDelay(redeliveryDelayMillis); - brokerRedeliveryPolicy.setInitialRedeliveryDelay(initialRedeliveryDelayMillis); - brokerRedeliveryPolicy.setMaximumRedeliveries(maxBrokerRedeliveries); - - RedeliveryPolicyMap redeliveryPolicyMap = new RedeliveryPolicyMap(); - redeliveryPolicyMap.setDefaultEntry(brokerRedeliveryPolicy); - redeliveryPlugin.setRedeliveryPolicyMap(redeliveryPolicyMap); - - broker.setPlugins(new BrokerPlugin[]{redeliveryPlugin}); - - if (deleteMessages) { - broker.setDeleteAllMessagesOnStartup(true); - } - broker.start(); - } - - private void stopBroker() throws Exception { - if (broker != null) - broker.stop(); - broker = null; - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://localhost"); - } - - @Override - protected void tearDown() throws Exception { - stopBroker(); - super.tearDown(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerServiceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerServiceTest.java deleted file mode 100644 index 5a22421bfd..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/BrokerServiceTest.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.activemq.broker; - -import junit.framework.TestCase; - -import org.apache.activemq.network.NetworkConnector; - -/** - * Tests for the BrokerService class - * - * @author chirino - */ -public class BrokerServiceTest extends TestCase { - - public void testAddRemoveTransportsWithJMX() throws Exception { - BrokerService service = new BrokerService(); - service.setUseJmx(true); - service.setPersistent(false); - TransportConnector connector = service.addConnector("tcp://localhost:0"); - service.start(); - - service.removeConnector(connector); - connector.stop(); - service.stop(); - } - - public void testAddRemoveTransportsWithoutJMX() throws Exception { - BrokerService service = new BrokerService(); - service.setPersistent(false); - service.setUseJmx(false); - TransportConnector connector = service.addConnector("tcp://localhost:0"); - service.start(); - - service.removeConnector(connector); - connector.stop(); - service.stop(); - } - - public void testAddRemoveNetworkWithJMX() throws Exception { - BrokerService service = new BrokerService(); - service.setPersistent(false); - service.setUseJmx(true); - NetworkConnector connector = service.addNetworkConnector("multicast://default?group=group-" + System.currentTimeMillis()); - service.start(); - - service.removeNetworkConnector(connector); - connector.stop(); - service.stop(); - } - - public void testAddRemoveNetworkWithoutJMX() throws Exception { - BrokerService service = new BrokerService(); - service.setPersistent(false); - service.setUseJmx(false); - NetworkConnector connector = service.addNetworkConnector("multicast://default?group=group-" + System.currentTimeMillis()); - service.start(); - - service.removeNetworkConnector(connector); - connector.stop(); - service.stop(); - } - - public void testSystemUsage() { - BrokerService service = new BrokerService(); - assertEquals(1024 * 1024 * 1024, service.getSystemUsage().getMemoryUsage().getLimit()); - assertEquals(1024L * 1024 * 1024 * 50, service.getSystemUsage().getTempUsage().getLimit()); - assertEquals(1024L * 1024 * 1024 * 100, service.getSystemUsage().getStoreUsage().getLimit()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ConcurrentConnectSimulationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ConcurrentConnectSimulationTest.java deleted file mode 100644 index b52d37b579..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ConcurrentConnectSimulationTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker; - -import junit.framework.Test; - -import org.apache.activemq.advisory.AdvisorySupport; -import org.apache.activemq.command.ConnectionInfo; -import org.apache.activemq.command.ConsumerId; -import org.apache.activemq.command.ConsumerInfo; -import org.apache.activemq.command.SessionId; - -public class ConcurrentConnectSimulationTest extends BrokerTestSupport { - - /* - * simulate failover and retry of connection before broker has killed connection - * which appears as a concurrent connect request to the broker - * see: https://issues.apache.org/activemq/browse/AMQ-2241 - */ - public void testConcurrentConnection() throws Exception { - - StubConnection connection1 = createConnection(); - StubConnection connection2 = createConnection(); - - // reuse same connection info - ConnectionInfo connectionInfo = createConnectionInfo(); - connection1.request(connectionInfo); - connection2.request(connectionInfo); - - // second one should win out, verify using consumer on default session (watchAdvisories) - ConsumerId consumerId = new ConsumerId(new SessionId(connectionInfo.getConnectionId(), -1), 1); - ConsumerInfo consumerInfo = new ConsumerInfo(consumerId); - consumerInfo.setDestination(AdvisorySupport.TEMP_DESTINATION_COMPOSITE_ADVISORY_TOPIC); - - connection2.request(consumerInfo); - } - - public static Test suite() { - return suite(ConcurrentConnectSimulationTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/CreateDestinationsOnStartupViaXBeanTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/CreateDestinationsOnStartupViaXBeanTest.java deleted file mode 100644 index 85dd17ebbb..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/CreateDestinationsOnStartupViaXBeanTest.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.activemq.broker; - -import java.net.URI; -import java.util.Set; - -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.broker.region.Destination; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.xbean.XBeanBrokerFactory; - -/** - * - * - */ -public class CreateDestinationsOnStartupViaXBeanTest extends EmbeddedBrokerTestSupport { - - public void testNewDestinationsAreCreatedOnStartup() throws Exception { - assertQueueCreated("FOO.BAR", true); - assertQueueCreated("FOO.DoesNotExist", false); - - assertTopicCreated("SOME.TOPIC", true); - assertTopicCreated("FOO.DoesNotExist", false); - } - - protected void assertQueueCreated(String name, boolean expected) throws Exception { - assertDestinationCreated(new ActiveMQQueue(name), expected); - } - - protected void assertTopicCreated(String name, boolean expected) throws Exception { - assertDestinationCreated(new ActiveMQTopic(name), expected); - } - - protected void assertDestinationCreated(ActiveMQDestination destination, boolean expected) throws Exception { - Set answer = broker.getBroker().getDestinations(destination); - int size = expected ? 1 : 0; - assertEquals("Could not find destination: " + destination + ". Size of found destinations: " + answer, size, answer.size()); - } - - @Override - protected BrokerService createBroker() throws Exception { - XBeanBrokerFactory factory = new XBeanBrokerFactory(); - BrokerService answer = factory.createBroker(new URI(getBrokerConfigUri())); - - // lets disable persistence as we are a test - answer.setPersistent(false); - - return answer; - } - - protected String getBrokerConfigUri() { - return "org/apache/activemq/broker/destinations-on-start.xml"; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DedicatedTaskRunnerBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DedicatedTaskRunnerBrokerTest.java deleted file mode 100644 index 156339ffe1..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DedicatedTaskRunnerBrokerTest.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.activemq.broker; - -import junit.framework.Test; - -public class DedicatedTaskRunnerBrokerTest extends BrokerTest { - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - broker.setDedicatedTaskRunner(true); - return broker; - } - - public static Test suite() { - return suite(DedicatedTaskRunnerBrokerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DoubleSubscriptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DoubleSubscriptionTest.java deleted file mode 100644 index b0bafe95a9..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DoubleSubscriptionTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker; - -import javax.jms.DeliveryMode; - -import junit.framework.Test; - -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ConnectionInfo; -import org.apache.activemq.command.ConsumerInfo; -import org.apache.activemq.command.Message; -import org.apache.activemq.command.MessageAck; -import org.apache.activemq.command.ProducerInfo; -import org.apache.activemq.command.SessionInfo; -import org.apache.activemq.network.NetworkTestSupport; - -/** - * Pretend to be an abusive client that sends multiple identical ConsumerInfo - * commands and make sure the broker doesn't stall because of it. - */ - -public class DoubleSubscriptionTest extends NetworkTestSupport { - - public ActiveMQDestination destination; - public int deliveryMode; - - private String remoteURI = "tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true"; - - public static Test suite() { - return suite(DoubleSubscriptionTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - public void initCombosForTestDoubleSubscription() { - addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST"), new ActiveMQQueue("TEST")}); - } - - public void testDoubleSubscription() throws Exception { - - // Start a normal consumer on the remote broker - StubConnection connection1 = createRemoteConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.request(consumerInfo1); - - // Start a normal producer on a remote broker - StubConnection connection2 = createRemoteConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.request(producerInfo2); - - // Send a message to make sure the basics are working - connection2.request(createMessage(producerInfo2, destination, DeliveryMode.PERSISTENT)); - - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNoMessagesLeft(connection1); - - connection1.send(createAck(consumerInfo1, m1, 1, MessageAck.STANDARD_ACK_TYPE)); - - // Send a message to sit on the broker while we mess with it - connection2.request(createMessage(producerInfo2, destination, DeliveryMode.PERSISTENT)); - - // Now we're going to resend the same consumer commands again and see if - // the broker - // can handle it. - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.request(consumerInfo1); - - // After this there should be 2 messages on the broker... - connection2.request(createMessage(producerInfo2, destination, DeliveryMode.PERSISTENT)); - - // ... let's start a fresh consumer... - connection1.stop(); - StubConnection connection3 = createRemoteConnection(); - ConnectionInfo connectionInfo3 = createConnectionInfo(); - SessionInfo sessionInfo3 = createSessionInfo(connectionInfo3); - ConsumerInfo consumerInfo3 = createConsumerInfo(sessionInfo3, destination); - connection3.send(connectionInfo3); - connection3.send(sessionInfo3); - connection3.request(consumerInfo3); - - // ... and then grab the 2 that should be there. - assertNotNull(receiveMessage(connection3)); - assertNotNull(receiveMessage(connection3)); - assertNoMessagesLeft(connection3); - } - - @Override - protected String getRemoteURI() { - return remoteURI; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DurablePersistentFalseRestartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DurablePersistentFalseRestartTest.java deleted file mode 100644 index 3cec506066..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/DurablePersistentFalseRestartTest.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.activemq.broker; - -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.jms.Topic; - -import junit.framework.Test; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.transport.failover.FailoverTransport; - -public class DurablePersistentFalseRestartTest extends BrokerRestartTestSupport { - - @Override - protected void configureBroker(BrokerService broker) throws Exception { - super.configureBroker(broker); - broker.setPersistent(false); - broker.setPersistenceAdapter(new KahaDBPersistenceAdapter()); - broker.addConnector("tcp://0.0.0.0:0"); - } - - public void testValidateNoPersistenceForDurableAfterRestart() throws Exception { - - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(" + broker.getTransportConnectors().get(0).getPublishableConnectString() + ")"); - ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.setClientID("clientId"); - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - Topic destination = session.createTopic(queueName); - MessageConsumer consumer = session.createDurableSubscriber(destination, "subscriberName"); - - populateDestination(10, destination, connection); - - restartBroker(); - - // make failover aware of the restarted auto assigned port - connection.getTransport().narrow(FailoverTransport.class).add(true, broker.getTransportConnectors().get(0).getPublishableConnectString()); - - TextMessage msg = (TextMessage) consumer.receive(4000); - assertNull("did not get a message when persistent=false, message: " + msg, msg); - - connection.close(); - } - - private void populateDestination(final int nbMessages, - final Destination destination, - javax.jms.Connection connection) throws JMSException { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - for (int i = 1; i <= nbMessages; i++) { - producer.send(session.createTextMessage("")); - } - producer.close(); - session.close(); - } - - public static Test suite() { - return suite(DurablePersistentFalseRestartTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/JdbcXARecoveryBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/JdbcXARecoveryBrokerTest.java deleted file mode 100644 index 467519ff24..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/JdbcXARecoveryBrokerTest.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.activemq.broker; - -import junit.framework.Test; - -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; -import org.apache.derby.jdbc.EmbeddedDataSource; -import org.apache.derby.jdbc.EmbeddedXADataSource; - -public class JdbcXARecoveryBrokerTest extends XARecoveryBrokerTest { - - EmbeddedXADataSource dataSource; - - @Override - protected void setUp() throws Exception { - dataSource = new EmbeddedXADataSource(); - dataSource.setDatabaseName("derbyDb"); - dataSource.setCreateDatabase("create"); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - stopDerby(); - } - - @Override - protected void configureBroker(BrokerService broker) throws Exception { - super.configureBroker(broker); - - JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); - jdbc.setDataSource(dataSource); - broker.setPersistenceAdapter(jdbc); - } - - @Override - protected void restartBroker() throws Exception { - broker.stop(); - stopDerby(); - dataSource = new EmbeddedXADataSource(); - dataSource.setDatabaseName("derbyDb"); - dataSource.setCreateDatabase("create"); - - broker = createRestartedBroker(); - broker.start(); - } - - private void stopDerby() { - LOG.info("STOPPING DB!@!!!!"); - final EmbeddedDataSource ds = dataSource; - try { - ds.setShutdownDatabase("shutdown"); - ds.getConnection(); - } catch (Exception ignored) { - } - - } - - public static Test suite() { - return suite(JdbcXARecoveryBrokerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - @Override - protected ActiveMQDestination createDestination() { - return new ActiveMQQueue("test,special"); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/Main.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/Main.java deleted file mode 100644 index d5bfc39bd3..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/Main.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker; - -import javax.jms.Connection; -import javax.jms.Session; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.jmx.ManagementContext; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.demo.DefaultQueueSender; - -/** - * A helper class which can be handy for running a broker in your IDE from the - * activemq-core module. - */ -public final class Main { - - protected static boolean createConsumers; - - private Main() { - } - - /** - * @param args - */ - public static void main(String[] args) { - try { - BrokerService broker = new BrokerService(); - broker.setPersistent(false); - - // String brokerDir = "xbean:...; - // System.setProperty("activemq.base", brokerDir); - // BrokerService broker = BrokerFactory.createBroker(new URI(brokerDir + "/activemq.xml")); - - // for running on Java 5 without mx4j - ManagementContext managementContext = broker.getManagementContext(); - managementContext.setFindTigerMbeanServer(true); - managementContext.setUseMBeanServer(true); - managementContext.setCreateConnector(false); - - broker.setUseJmx(true); - // broker.setPlugins(new BrokerPlugin[] { new - // ConnectionDotFilePlugin(), new UDPTraceBrokerPlugin() }); - broker.addConnector("tcp://localhost:61616"); - broker.addConnector("stomp://localhost:61613"); - broker.start(); - - // lets publish some messages so that there is some stuff to browse - DefaultQueueSender.main(new String[]{"Prices.Equity.IBM"}); - DefaultQueueSender.main(new String[]{"Prices.Equity.MSFT"}); - - // lets create a dummy couple of consumers - if (createConsumers) { - Connection connection = new ActiveMQConnectionFactory().createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createConsumer(new ActiveMQQueue("Orders.IBM")); - session.createConsumer(new ActiveMQQueue("Orders.MSFT"), "price > 100"); - Session session2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session2.createConsumer(new ActiveMQQueue("Orders.MSFT"), "price > 200"); - } else { - // Lets wait for the broker - broker.waitUntilStopped(); - } - } catch (Exception e) { - System.out.println("Failed: " + e); - e.printStackTrace(); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/MarshallingBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/MarshallingBrokerTest.java deleted file mode 100644 index 52ba940536..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/MarshallingBrokerTest.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.activemq.broker; - -import java.io.IOException; - -import junit.framework.Test; - -import org.apache.activemq.command.Command; -import org.apache.activemq.command.Response; -import org.apache.activemq.openwire.OpenWireFormat; -import org.apache.activemq.wireformat.WireFormat; - -/** - * Runs against the broker but marshals all request and response commands. - */ -public class MarshallingBrokerTest extends BrokerTest { - - public WireFormat wireFormat = new OpenWireFormat(); - - public void initCombos() { - - OpenWireFormat wf1 = new OpenWireFormat(); - wf1.setCacheEnabled(false); - OpenWireFormat wf2 = new OpenWireFormat(); - wf2.setCacheEnabled(true); - - addCombinationValues("wireFormat", new Object[]{wf1, wf2,}); - } - - @Override - protected StubConnection createConnection() throws Exception { - return new StubConnection(broker) { - @Override - public Response request(Command command) throws Exception { - Response r = super.request((Command) wireFormat.unmarshal(wireFormat.marshal(command))); - if (r != null) { - r = (Response) wireFormat.unmarshal(wireFormat.marshal(r)); - } - return r; - } - - @Override - public void send(Command command) throws Exception { - super.send((Command) wireFormat.unmarshal(wireFormat.marshal(command))); - } - - protected void dispatch(Command command) throws InterruptedException, IOException { - super.dispatch(wireFormat.unmarshal(wireFormat.marshal(command))); - } - }; - } - - public static Test suite() { - return suite(MarshallingBrokerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/MessageExpirationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/MessageExpirationTest.java deleted file mode 100644 index 6d5ef5c54f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/MessageExpirationTest.java +++ /dev/null @@ -1,276 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker; - -import javax.jms.DeliveryMode; - -import junit.framework.Test; - -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.VMPendingSubscriberMessageStoragePolicy; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ConnectionInfo; -import org.apache.activemq.command.ConsumerInfo; -import org.apache.activemq.command.LocalTransactionId; -import org.apache.activemq.command.Message; -import org.apache.activemq.command.MessageAck; -import org.apache.activemq.command.ProducerInfo; -import org.apache.activemq.command.SessionInfo; - -public class MessageExpirationTest extends BrokerTestSupport { - - public ActiveMQDestination destination; - public int deliveryMode = DeliveryMode.NON_PERSISTENT; - public int prefetch; - public byte destinationType = ActiveMQDestination.QUEUE_TYPE; - public boolean durableConsumer; - - protected Message createMessage(ProducerInfo producerInfo, - ActiveMQDestination destination, - int deliveryMode, - int timeToLive) { - Message message = createMessage(producerInfo, destination, deliveryMode); - long now = System.currentTimeMillis(); - message.setTimestamp(now); - message.setExpiration(now + timeToLive); - return message; - } - - public void initCombosForTestMessagesWaitingForUssageDecreaseExpire() { - addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); - } - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setPersistent(false); - return broker; - } - - @Override - protected PolicyEntry getDefaultPolicy() { - PolicyEntry policy = super.getDefaultPolicy(); - // disable spooling - policy.setPendingSubscriberPolicy(new VMPendingSubscriberMessageStoragePolicy()); - // have aggressive expiry period to ensure no deadlock or clash - policy.setExpireMessagesPeriod(100); - - return policy; - } - - public void testMessagesWaitingForUsageDecreaseExpire() throws Exception { - - // Start a producer - final StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - final ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - // Start a consumer.. - final StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - - destination = createDestinationInfo(connection2, connectionInfo2, destinationType); - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - consumerInfo2.setPrefetchSize(1); - connection2.request(consumerInfo2); - - // Reduce the limit so that only 1 message can flow through the broker - // at a time. - broker.getSystemUsage().getMemoryUsage().setLimit(1); - - final Message m1 = createMessage(producerInfo, destination, deliveryMode); - final Message m2 = createMessage(producerInfo, destination, deliveryMode, 1000); - final Message m3 = createMessage(producerInfo, destination, deliveryMode); - final Message m4 = createMessage(producerInfo, destination, deliveryMode, 1000); - - // Produce in an async thread since the producer will be getting blocked - // by the usage manager.. - new Thread() { - @Override - public void run() { - // m1 and m3 should not expire.. but the others should. - try { - connection.send(m1); - connection.send(m2); - connection.send(m3); - connection.send(m4); - } catch (Exception e) { - e.printStackTrace(); - } - } - }.start(); - - // Make sure only 1 message was delivered due to prefetch == 1 - Message m = receiveMessage(connection2); - assertNotNull(m); - assertEquals(m1.getMessageId(), m.getMessageId()); - assertNoMessagesLeft(connection); - - // Sleep before we ack so that the messages expire on the usage manager - Thread.sleep(1500); - connection2.send(createAck(consumerInfo2, m, 1, MessageAck.STANDARD_ACK_TYPE)); - - // 2nd message received should be m3.. it should have expired 2nd - // message sent. - m = receiveMessage(connection2); - assertNotNull(m); - assertEquals(m3.getMessageId(), m.getMessageId()); - - // Sleep before we ack so that the messages expire on the usage manager - Thread.sleep(1500); - connection2.send(createAck(consumerInfo2, m, 1, MessageAck.STANDARD_ACK_TYPE)); - - // And there should be no messages left now.. - assertNoMessagesLeft(connection2); - - connection.send(closeConnectionInfo(connectionInfo)); - connection.send(closeConnectionInfo(connectionInfo2)); - } - - public void initCombosForTestMessagesInLongTransactionExpire() { - addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.PERSISTENT), Integer.valueOf(DeliveryMode.NON_PERSISTENT)}); - addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); - } - - public void testMessagesInLongTransactionExpire() throws Exception { - - // Start a producer and consumer - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - destination = createDestinationInfo(connection, connectionInfo, destinationType); - - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setPrefetchSize(1000); - connection.send(consumerInfo); - - // Start the tx.. - LocalTransactionId txid = createLocalTransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - // m1 and m3 should not expire.. but the others should. - Message m1 = createMessage(producerInfo, destination, deliveryMode); - m1.setTransactionId(txid); - connection.send(m1); - Message m = createMessage(producerInfo, destination, deliveryMode, 1000); - m.setTransactionId(txid); - connection.send(m); - Message m3 = createMessage(producerInfo, destination, deliveryMode); - m3.setTransactionId(txid); - connection.send(m3); - m = createMessage(producerInfo, destination, deliveryMode, 1000); - m.setTransactionId(txid); - connection.send(m); - - // Sleep before we commit so that the messages expire on the commit - // list.. - Thread.sleep(1500); - connection.send(createCommitTransaction1Phase(connectionInfo, txid)); - - m = receiveMessage(connection); - assertNotNull(m); - assertEquals(m1.getMessageId(), m.getMessageId()); - connection.send(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); - - // 2nd message received should be m3.. it should have expired 2nd - // message sent. - m = receiveMessage(connection); - assertNotNull(m); - assertEquals(m3.getMessageId(), m.getMessageId()); - connection.send(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); - - // And there should be no messages left now.. - assertNoMessagesLeft(connection); - - connection.send(closeConnectionInfo(connectionInfo)); - } - - public void initCombosForTestMessagesInSubscriptionPendingListExpire() { - addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); - } - - public void testMessagesInSubscriptionPendingListExpire() throws Exception { - - // Start a producer and consumer - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - destination = createDestinationInfo(connection, connectionInfo, destinationType); - - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setPrefetchSize(1); - connection.send(consumerInfo); - - // m1 and m3 should not expire.. but the others should. - Message m1 = createMessage(producerInfo, destination, deliveryMode); - connection.send(m1); - connection.send(createMessage(producerInfo, destination, deliveryMode, 1000)); - Message m3 = createMessage(producerInfo, destination, deliveryMode); - connection.send(m3); - connection.send(createMessage(producerInfo, destination, deliveryMode, 1000)); - - // Make sure only 1 message was delivered due to prefetch == 1 - Message m = receiveMessage(connection); - assertNotNull(m); - assertEquals(m1.getMessageId(), m.getMessageId()); - assertNoMessagesLeft(connection); - - // Sleep before we ack so that the messages expire on the pending list.. - Thread.sleep(1500); - connection.send(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); - - // 2nd message received should be m3.. it should have expired 2nd - // message sent. - m = receiveMessage(connection); - assertNotNull(m); - assertEquals(m3.getMessageId(), m.getMessageId()); - connection.send(createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE)); - - // And there should be no messages left now.. - assertNoMessagesLeft(connection); - - connection.send(closeConnectionInfo(connectionInfo)); - } - - public static Test suite() { - return suite(MessageExpirationTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/NioQueueSubscriptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/NioQueueSubscriptionTest.java deleted file mode 100644 index e905774a97..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/NioQueueSubscriptionTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker; - -import javax.jms.ConnectionFactory; -import javax.jms.ExceptionListener; -import javax.jms.JMSException; -import java.net.URI; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.BlockJUnit4ClassRunner; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -@RunWith(BlockJUnit4ClassRunner.class) -public class NioQueueSubscriptionTest extends QueueSubscriptionTest { - - protected static final Logger LOG = LoggerFactory.getLogger(NioQueueSubscriptionTest.class); - - private final Map exceptions = Collections.synchronizedMap(new HashMap()); - - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("tcp://localhost:62621?trace=false"); - } - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService answer = BrokerFactory.createBroker(new URI("broker://nio://localhost:62621?useQueueForAccept=false&persistent=false&wiewformat.maxInactivityDuration=0")); - answer.getManagementContext().setCreateConnector(false); - answer.setUseJmx(false); - answer.setDeleteAllMessagesOnStartup(true); - final List policyEntries = new ArrayList<>(); - final PolicyEntry entry = new PolicyEntry(); - entry.setQueue(">"); - entry.setOptimizedDispatch(true); - policyEntries.add(entry); - - final PolicyMap policyMap = new PolicyMap(); - policyMap.setPolicyEntries(policyEntries); - answer.setDestinationPolicy(policyMap); - return answer; - } - - @Ignore("See AMQ-4286") - @Test(timeout = 60 * 1000) - public void testLotsOfConcurrentConnections() throws Exception { - ExecutorService executor = Executors.newCachedThreadPool(); - final ConnectionFactory factory = createConnectionFactory(); - int connectionCount = 400; - final AtomicInteger threadId = new AtomicInteger(0); - for (int i = 0; i < connectionCount; i++) { - executor.execute(new Runnable() { - @Override - public void run() { - final int innerId = threadId.incrementAndGet(); - try { - ExceptionListener listener = new NioQueueSubscriptionTestListener(innerId, exceptions, LOG); - ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection(); - connection.setExceptionListener(listener); - connection.start(); - assertNotNull(connection.getBrokerName()); - connections.add(connection); - } catch (Exception e) { - LOG.error(">>>> Exception in run() on thread " + innerId, e); - exceptions.put(Thread.currentThread(), e); - } - } - }); - } - - executor.shutdown(); - executor.awaitTermination(30, TimeUnit.SECONDS); - - if (!exceptions.isEmpty()) { - LOG.error(">>>> " + exceptions.size() + " exceptions like", exceptions.values().iterator().next()); - fail("unexpected exceptions in worker threads: " + exceptions.values().iterator().next()); - } - LOG.info("created " + connectionCount + " connections"); - } -} - -class NioQueueSubscriptionTestListener implements ExceptionListener { - - private int id = 0; - protected Logger LOG; - private final Map exceptions; - - public NioQueueSubscriptionTestListener(int id, Map exceptions, Logger log) { - this.id = id; - this.exceptions = exceptions; - this.LOG = log; - } - - @Override - public void onException(JMSException exception) { - LOG.error(">>>> Exception in onException() on thread " + id, exception); - exceptions.put(Thread.currentThread(), exception); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/OutOfOrderXMLTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/OutOfOrderXMLTest.java deleted file mode 100644 index fa9d09e37f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/OutOfOrderXMLTest.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.activemq.broker; - -import java.net.URI; - -import org.junit.Test; - -// https://issues.apache.org/activemq/browse/AMQ-2939 -public class OutOfOrderXMLTest { - - @Test - public void verifyBrokerCreationWhenXmlOutOfOrderValidationFalse() throws Exception { - BrokerService answer = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/broker/out-of-order-broker-elements.xml?validate=false")); - answer.stop(); - - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/QueueMbeanRestartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/QueueMbeanRestartTest.java deleted file mode 100644 index 711409b272..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/QueueMbeanRestartTest.java +++ /dev/null @@ -1,123 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker; - -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.management.ObjectName; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.apache.activemq.TestSupport; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.util.JMXSupport; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@RunWith(value = Parameterized.class) -public class QueueMbeanRestartTest extends TestSupport { - - private static final transient Logger LOG = LoggerFactory.getLogger(QueueMbeanRestartTest.class); - - BrokerService broker; - - private final TestSupport.PersistenceAdapterChoice persistenceAdapterChoice; - - @Parameterized.Parameters - public static Collection getTestParameters() { - TestSupport.PersistenceAdapterChoice[] kahaDb = {TestSupport.PersistenceAdapterChoice.KahaDB}; - TestSupport.PersistenceAdapterChoice[] levelDb = {TestSupport.PersistenceAdapterChoice.LevelDB}; - TestSupport.PersistenceAdapterChoice[] jdbc = {TestSupport.PersistenceAdapterChoice.JDBC}; - List choices = new ArrayList<>(); - choices.add(kahaDb); - choices.add(levelDb); - choices.add(jdbc); - - return choices; - } - - public QueueMbeanRestartTest(TestSupport.PersistenceAdapterChoice choice) { - this.persistenceAdapterChoice = choice; - } - - @Override - @Before - public void setUp() throws Exception { - topic = false; - super.setUp(); - } - - @Override - @After - public void tearDown() throws Exception { - super.tearDown(); - broker.stop(); - } - - @Test(timeout = 60000) - public void testMBeanPresenceOnRestart() throws Exception { - createBroker(true); - - sendMessages(); - verifyPresenceOfQueueMbean(); - LOG.info("restart...."); - - restartBroker(); - verifyPresenceOfQueueMbean(); - } - - private void restartBroker() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - Thread.sleep(5 * 1000); - createBroker(false); - broker.waitUntilStarted(); - } - - private void verifyPresenceOfQueueMbean() throws Exception { - for (ObjectName name : broker.getManagementContext().queryNames(null, null)) { - LOG.info("candidate :" + name); - String type = name.getKeyProperty("destinationType"); - if (type != null && type.equals("Queue")) { - assertEquals(JMXSupport.encodeObjectNamePart(((ActiveMQQueue) createDestination()).getPhysicalName()), name.getKeyProperty("destinationName")); - LOG.info("found mbbean " + name); - return; - } - } - fail("expected to find matching queue mbean for: " + createDestination()); - } - - private void sendMessages() throws Exception { - Session session = createConnection().createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(createDestination()); - producer.send(session.createTextMessage()); - } - - private void createBroker(boolean deleteAll) throws Exception { - broker = new BrokerService(); - setPersistenceAdapter(broker, persistenceAdapterChoice); - - broker.setDeleteAllMessagesOnStartup(deleteAll); - broker.start(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/QueueSubscriptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/QueueSubscriptionTest.java deleted file mode 100644 index ac282f886b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/QueueSubscriptionTest.java +++ /dev/null @@ -1,188 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.JmsMultipleClientsTestSupport; -import org.apache.activemq.command.ActiveMQDestination; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.BlockJUnit4ClassRunner; - -@RunWith(BlockJUnit4ClassRunner.class) -public class QueueSubscriptionTest extends JmsMultipleClientsTestSupport { - - protected int messageCount = 1000; // 1000 Messages per producer - protected int prefetchCount = 10; - - @Before - @Override - public void setUp() throws Exception { - super.setUp(); - durable = false; - topic = false; - } - - @After - @Override - public void tearDown() throws Exception { - super.tearDown(); - } - - @Test(timeout = 60 * 1000) - public void testManyProducersOneConsumer() throws Exception { - consumerCount = 1; - producerCount = 10; - messageCount = 100; - messageSize = 1; // 1 byte - prefetchCount = 10; - - doMultipleClientsTest(); - - assertTotalMessagesReceived(messageCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } - - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersSmallMessagesOnePrefetch() throws Exception { - consumerCount = 2; - producerCount = 1; - messageCount = 1000; - messageSize = 1024; // 1 Kb - configurePrefetchOfOne(); - - doMultipleClientsTest(); - - assertTotalMessagesReceived(messageCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } - - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersSmallMessagesLargePrefetch() throws Exception { - consumerCount = 2; - producerCount = 1; - messageCount = 1000; - prefetchCount = messageCount * 2; - messageSize = 1024; // 1 Kb - - doMultipleClientsTest(); - - assertTotalMessagesReceived(messageCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } - - @Test(timeout = 2 * 60 * 1000) - public void testOneProducerTwoConsumersLargeMessagesOnePrefetch() throws Exception { - consumerCount = 2; - producerCount = 1; - messageCount = 10; - messageSize = 1024 * 1024 * 1; // 2 MB - configurePrefetchOfOne(); - - doMultipleClientsTest(); - - assertTotalMessagesReceived(messageCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } - - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersLargeMessagesLargePrefetch() throws Exception { - consumerCount = 2; - producerCount = 1; - messageCount = 10; - prefetchCount = messageCount * 2; - messageSize = 1024 * 1024 * 1; // 2 MB - - doMultipleClientsTest(); - - assertTotalMessagesReceived(messageCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } - - @Test(timeout = 60 * 1000) - public void testOneProducerManyConsumersFewMessages() throws Exception { - consumerCount = 50; - producerCount = 1; - messageCount = 10; - messageSize = 1; // 1 byte - prefetchCount = 10; - - doMultipleClientsTest(); - - assertTotalMessagesReceived(messageCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } - - @Test(timeout = 60 * 1000) - public void testOneProducerManyConsumersManyMessages() throws Exception { - consumerCount = 50; - producerCount = 1; - messageCount = 1000; - messageSize = 1; // 1 byte - prefetchCount = messageCount / consumerCount; - allMessagesList.setMaximumDuration(allMessagesList.getMaximumDuration() * 20); - doMultipleClientsTest(); - - assertTotalMessagesReceived(messageCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } - - @Test(timeout = 2 * 60 * 1000) - public void testManyProducersManyConsumers() throws Exception { - consumerCount = 200; - producerCount = 50; - messageCount = 100; - messageSize = 1; // 1 byte - prefetchCount = 100; - allMessagesList.setMaximumDuration(allMessagesList.getMaximumDuration() * 20); - doMultipleClientsTest(); - - assertTotalMessagesReceived(messageCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } - - protected void configurePrefetchOfOne() { - prefetchCount = 1; - - // this is gonna be a bit slow what with the low prefetch so bump up the - // wait time - allMessagesList.setMaximumDuration(allMessagesList.getMaximumDuration() * 20); - } - - public void doMultipleClientsTest() throws Exception { - // Create destination - final ActiveMQDestination dest = createDestination(); - - // Create consumers - ActiveMQConnectionFactory consumerFactory = (ActiveMQConnectionFactory) createConnectionFactory(); - consumerFactory.getPrefetchPolicy().setAll(prefetchCount); - - startConsumers(consumerFactory, dest); - - startProducers(dest, messageCount); - - // Wait for messages to be received. Make it proportional to the - // messages delivered. - int totalMessageCount = messageCount * producerCount; - if (dest.isTopic()) { - totalMessageCount *= consumerCount; - } - waitForAllMessagesToBeReceived(totalMessageCount); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ReconnectWithJMXEnabledTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ReconnectWithJMXEnabledTest.java deleted file mode 100644 index 7bcfe913d3..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ReconnectWithJMXEnabledTest.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.activemq.broker; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.EmbeddedBrokerTestSupport; - -/** - * - * - */ -public class ReconnectWithJMXEnabledTest extends EmbeddedBrokerTestSupport { - - protected Connection connection; - protected boolean transacted; - protected int authMode = Session.AUTO_ACKNOWLEDGE; - - public void testTestUseConnectionCloseBrokerThenRestartInSameJVM() throws Exception { - connection = connectionFactory.createConnection(); - useConnection(connection); - connection.close(); - - broker.stop(); - broker = createBroker(); - startBroker(); - - connectionFactory = createConnectionFactory(); - connection = connectionFactory.createConnection(); - useConnection(connection); - } - - @Override - protected void setUp() throws Exception { - bindAddress = "tcp://localhost:0"; - super.setUp(); - } - - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); - } - - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - connection = null; - } - super.tearDown(); - } - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setUseJmx(true); - answer.setPersistent(isPersistent()); - answer.addConnector(bindAddress); - return answer; - } - - protected void useConnection(Connection connection) throws Exception { - connection.setClientID("foo"); - connection.start(); - Session session = connection.createSession(transacted, authMode); - Destination destination = createDestination(); - MessageConsumer consumer = session.createConsumer(destination); - MessageProducer producer = session.createProducer(destination); - Message message = session.createTextMessage("Hello World"); - producer.send(message); - Thread.sleep(1000); - consumer.close(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RecoveryBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RecoveryBrokerTest.java deleted file mode 100644 index 9c6aa1fc9b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RecoveryBrokerTest.java +++ /dev/null @@ -1,580 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker; - -import javax.jms.DeliveryMode; -import java.util.ArrayList; - -import junit.framework.Test; - -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.command.ConnectionInfo; -import org.apache.activemq.command.ConsumerInfo; -import org.apache.activemq.command.LocalTransactionId; -import org.apache.activemq.command.Message; -import org.apache.activemq.command.MessageAck; -import org.apache.activemq.command.MessageId; -import org.apache.activemq.command.ProducerInfo; -import org.apache.activemq.command.SessionInfo; -import org.apache.activemq.command.XATransactionId; - -/** - * Used to simulate the recovery that occurs when a broker shuts down. - */ -public class RecoveryBrokerTest extends BrokerRestartTestSupport { - - /** - * Used to verify that after a broker restart durable subscriptions that use - * wild cards are still wild card subscription after broker restart. - * - * @throws Exception - */ - //need to revist!!! - public void XtestWildCardSubscriptionPreservedOnRestart() throws Exception { - ActiveMQDestination dest1 = new ActiveMQTopic("TEST.A"); - ActiveMQDestination dest2 = new ActiveMQTopic("TEST.B"); - ActiveMQDestination dest3 = new ActiveMQTopic("TEST.C"); - ActiveMQDestination wildDest = new ActiveMQTopic("TEST.>"); - - ArrayList sentBeforeRestart = new ArrayList<>(); - ArrayList sentBeforeCreateConsumer = new ArrayList<>(); - ArrayList sentAfterCreateConsumer = new ArrayList<>(); - - // Setup a first connection - { - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - connectionInfo1.setClientId("A"); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo1); - - // Create the durable subscription. - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, wildDest); - consumerInfo1.setSubscriptionName("test"); - consumerInfo1.setPrefetchSize(100); - connection1.send(consumerInfo1); - - // Close the subscription. - connection1.send(closeConsumerInfo(consumerInfo1)); - - // Send the messages - for (int i = 0; i < 4; i++) { - Message m = createMessage(producerInfo1, dest1, DeliveryMode.PERSISTENT); - connection1.send(m); - sentBeforeRestart.add(m.getMessageId()); - } - connection1.request(closeConnectionInfo(connectionInfo1)); - connection1.stop(); - } - - // Restart the broker. - restartBroker(); - - // Get a connection to the new broker. - { - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - connectionInfo2.setClientId("A"); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - - ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); - connection2.send(producerInfo2); - - // Send messages before the durable subscription is re-activated. - for (int i = 0; i < 4; i++) { - Message m = createMessage(producerInfo2, dest2, DeliveryMode.PERSISTENT); - connection2.send(m); - sentBeforeCreateConsumer.add(m.getMessageId()); - } - - // Re-open the subscription. - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, wildDest); - consumerInfo2.setSubscriptionName("test"); - consumerInfo2.setPrefetchSize(100); - connection2.send(consumerInfo2); - - // Send messages after the subscription is activated. - for (int i = 0; i < 4; i++) { - Message m = createMessage(producerInfo2, dest3, DeliveryMode.PERSISTENT); - connection2.send(m); - sentAfterCreateConsumer.add(m.getMessageId()); - } - - // We should get the recovered messages... - for (int i = 0; i < 4; i++) { - Message m2 = receiveMessage(connection2); - assertNotNull("Recovered message missing: " + i, m2); - assertEquals(sentBeforeRestart.get(i), m2.getMessageId()); - } - - // We should get get the messages that were sent before the sub was - // reactivated. - for (int i = 0; i < 4; i++) { - Message m2 = receiveMessage(connection2); - assertNotNull("Before activated message missing: " + i, m2); - assertEquals(sentBeforeCreateConsumer.get(i), m2.getMessageId()); - } - - // We should get get the messages that were sent after the sub was - // reactivated. - for (int i = 0; i < 4; i++) { - Message m2 = receiveMessage(connection2); - assertNotNull("After activated message missing: " + i, m2); - assertEquals("" + i, sentAfterCreateConsumer.get(i), m2.getMessageId()); - } - - assertNoMessagesLeft(connection2); - } - - } - - public void testConsumedQueuePersistentMessagesLostOnRestart() throws Exception { - - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } - - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // The we should get the messages. - for (int i = 0; i < 4; i++) { - Message m2 = receiveMessage(connection); - assertNotNull(m2); - } - - // restart the broker. - restartBroker(); - - // No messages should be delivered. - Message m = receiveMessage(connection); - assertNull(m); - } - - public void testQueuePersistentUncommitedMessagesLostOnRestart() throws Exception { - - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - // Begin the transaction. - LocalTransactionId txid = createLocalTransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - message.setTransactionId(txid); - connection.send(message); - } - - // Don't commit - - // restart the broker. - restartBroker(); - - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // No messages should be delivered. - Message m = receiveMessage(connection); - assertNull(m); - } - - public void testTopicDurableConsumerHoldsPersistentMessageAfterRestart() throws Exception { - - ActiveMQDestination destination = new ActiveMQTopic("TEST"); - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - connectionInfo1.setClientId("A"); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo1 = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo1); - - // Create the durable subscription. - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setSubscriptionName("test"); - consumerInfo1.setPrefetchSize(100); - connection1.send(consumerInfo1); - - // Close the subscription. - connection1.send(closeConsumerInfo(consumerInfo1)); - - // Send the messages - connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); - connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); - connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); - connection1.send(createMessage(producerInfo1, destination, DeliveryMode.PERSISTENT)); - connection1.request(closeConnectionInfo(connectionInfo1)); - // Restart the broker. - restartBroker(); - - // Get a connection to the new broker. - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - connectionInfo2.setClientId("A"); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - - // Re-open the subscription. - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - consumerInfo2.setSubscriptionName("test"); - consumerInfo2.setPrefetchSize(100); - connection2.send(consumerInfo2); - - // The we should get the messages. - for (int i = 0; i < 4; i++) { - Message m2 = receiveMessage(connection2); - assertNotNull("Did not get message " + i, m2); - } - assertNoMessagesLeft(connection2); - } - - public void testQueuePersistentMessagesNotLostOnRestart() throws Exception { - - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - connection.request(closeConnectionInfo(connectionInfo)); - - // restart the broker. - restartBroker(); - - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // Message should have been dropped due to broker restart. - Message m = receiveMessage(connection); - assertNotNull("Should have received a message by now!", m); - assertEquals(m.getMessageId(), message.getMessageId()); - } - - public void testQueueNonPersistentMessagesLostOnRestart() throws Exception { - - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - Message message = createMessage(producerInfo, destination); - message.setPersistent(false); - connection.send(message); - - // restart the broker. - restartBroker(); - - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // Message should have been dropped due to broker restart. - assertNoMessagesLeft(connection); - } - - public void testQueuePersistentCommittedMessagesNotLostOnRestart() throws Exception { - - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - // Begin the transaction. - LocalTransactionId txid = createLocalTransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - message.setTransactionId(txid); - connection.send(message); - } - - // Commit - connection.send(createCommitTransaction1Phase(connectionInfo, txid)); - connection.request(closeConnectionInfo(connectionInfo)); - // restart the broker. - restartBroker(); - - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - for (int i = 0; i < 4; i++) { - Message m = receiveMessage(connection); - assertNotNull(m); - } - - assertNoMessagesLeft(connection); - } - - public void testQueuePersistentCommittedAcksNotLostOnRestart() throws Exception { - - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } - - // Setup the consumer and receive the message. - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // Begin the transaction. - LocalTransactionId txid = createLocalTransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - for (int i = 0; i < 4; i++) { - Message m = receiveMessage(connection); - assertNotNull(m); - MessageAck ack = createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - } - // Commit - connection.send(createCommitTransaction1Phase(connectionInfo, txid)); - connection.request(closeConnectionInfo(connectionInfo)); - // restart the broker. - restartBroker(); - - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // No messages should be delivered. - Message m = receiveMessage(connection); - assertNull(m); - } - - public void testQueuePersistentUncommitedAcksLostOnRestart() throws Exception { - - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } - - // Setup the consumer and receive the message. - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // Begin the transaction. - LocalTransactionId txid = createLocalTransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - for (int i = 0; i < 4; i++) { - Message m = receiveMessage(connection); - assertNotNull(m); - MessageAck ack = createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - } - // Don't commit - - // restart the broker. - restartBroker(); - - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // All messages should be re-delivered. - for (int i = 0; i < 4; i++) { - Message m = receiveMessage(connection); - assertNotNull(m); - } - - assertNoMessagesLeft(connection); - } - - public void testQueuePersistentXAUncommitedAcksLostOnRestart() throws Exception { - int NUMBER = 100; - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - for (int i = 0; i < NUMBER; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } - - // Setup the consumer and receive the message. - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - Message m = null; - for (int i = 0; i < NUMBER; i++) { - m = receiveMessage(connection); - assertNotNull(m); - } - MessageAck ack = createAck(consumerInfo, m, NUMBER, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - - // Don't commit - - // restart the broker. - restartBroker(); - - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // All messages should be re-delivered. - for (int i = 0; i < NUMBER; i++) { - m = receiveMessage(connection); - assertNotNull(m); - } - - assertNoMessagesLeft(connection); - } - - public static Test suite() { - return suite(RecoveryBrokerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RedeliveryRestartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RedeliveryRestartTest.java deleted file mode 100644 index 302f9f2e5f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RedeliveryRestartTest.java +++ /dev/null @@ -1,293 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker; - -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.jms.TopicSubscriber; -import java.util.Arrays; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.TestSupport; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.transport.failover.FailoverTransport; -import org.junit.After; -import org.junit.Before; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@RunWith(value = Parameterized.class) -public class RedeliveryRestartTest extends TestSupport { - - private static final transient Logger LOG = LoggerFactory.getLogger(RedeliveryRestartTest.class); - ActiveMQConnection connection; - BrokerService broker = null; - String queueName = "redeliveryRestartQ"; - - @Parameterized.Parameter - public TestSupport.PersistenceAdapterChoice persistenceAdapterChoice = PersistenceAdapterChoice.KahaDB; - - @Parameterized.Parameters(name = "Store={0}") - public static Iterable data() { - return Arrays.asList(new Object[][]{{TestSupport.PersistenceAdapterChoice.KahaDB}, {TestSupport.PersistenceAdapterChoice.JDBC}, {TestSupport.PersistenceAdapterChoice.LevelDB}}); - } - - @Override - @Before - public void setUp() throws Exception { - super.setUp(); - broker = new BrokerService(); - configureBroker(broker); - broker.setDeleteAllMessagesOnStartup(true); - broker.start(); - } - - @Override - @After - public void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - broker.stop(); - super.tearDown(); - } - - protected void configureBroker(BrokerService broker) throws Exception { - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policy = new PolicyEntry(); - policy.setPersistJMSRedelivered(true); - policyMap.setDefaultEntry(policy); - broker.setDestinationPolicy(policyMap); - setPersistenceAdapter(broker, persistenceAdapterChoice); - broker.addConnector("tcp://0.0.0.0:0"); - } - - @org.junit.Test - public void testValidateRedeliveryFlagAfterRestartNoTx() throws Exception { - - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(" + broker.getTransportConnectors().get(0).getPublishableConnectString() + ")?jms.prefetchPolicy.all=0"); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Destination destination = session.createQueue(queueName); - populateDestination(10, destination, connection); - - MessageConsumer consumer = session.createConsumer(destination); - TextMessage msg = null; - for (int i = 0; i < 5; i++) { - msg = (TextMessage) consumer.receive(20000); - LOG.info("not redelivered? got: " + msg); - assertNotNull("got the message", msg); - assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); - assertEquals("not a redelivery", false, msg.getJMSRedelivered()); - } - consumer.close(); - - restartBroker(); - - // make failover aware of the restarted auto assigned port - connection.getTransport().narrow(FailoverTransport.class).add(true, broker.getTransportConnectors().get(0).getPublishableConnectString()); - - consumer = session.createConsumer(destination); - for (int i = 0; i < 5; i++) { - msg = (TextMessage) consumer.receive(4000); - LOG.info("redelivered? got: " + msg); - assertNotNull("got the message again", msg); - assertEquals("re delivery flag", true, msg.getJMSRedelivered()); - assertEquals("redelivery count survives restart", 2, msg.getLongProperty("JMSXDeliveryCount")); - msg.acknowledge(); - } - - // consume the rest that were not redeliveries - for (int i = 0; i < 5; i++) { - msg = (TextMessage) consumer.receive(20000); - LOG.info("not redelivered? got: " + msg); - assertNotNull("got the message", msg); - assertEquals("not a redelivery", false, msg.getJMSRedelivered()); - assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); - msg.acknowledge(); - } - connection.close(); - } - - @org.junit.Test - public void testDurableSubRedeliveryFlagAfterRestartNotSupported() throws Exception { - - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(" + broker.getTransportConnectors().get(0).getPublishableConnectString() + ")?jms.prefetchPolicy.all=0"); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.setClientID("id"); - connection.start(); - - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - ActiveMQTopic destination = new ActiveMQTopic(queueName); - - TopicSubscriber durableSub = session.createDurableSubscriber(destination, "id"); - - populateDestination(10, destination, connection); - - TextMessage msg = null; - for (int i = 0; i < 5; i++) { - msg = (TextMessage) durableSub.receive(20000); - LOG.info("not redelivered? got: " + msg); - assertNotNull("got the message", msg); - assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); - assertEquals("not a redelivery", false, msg.getJMSRedelivered()); - } - durableSub.close(); - - restartBroker(); - - // make failover aware of the restarted auto assigned port - connection.getTransport().narrow(FailoverTransport.class).add(true, broker.getTransportConnectors().get(0).getPublishableConnectString()); - - durableSub = session.createDurableSubscriber(destination, "id"); - for (int i = 0; i < 10; i++) { - msg = (TextMessage) durableSub.receive(4000); - LOG.info("redelivered? got: " + msg); - assertNotNull("got the message again", msg); - assertEquals("no reDelivery flag", false, msg.getJMSRedelivered()); - msg.acknowledge(); - } - connection.close(); - } - - @org.junit.Test - public void testValidateRedeliveryFlagAfterRestart() throws Exception { - - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(" + broker.getTransportConnectors().get(0).getPublishableConnectString() + ")?jms.prefetchPolicy.all=0"); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Destination destination = session.createQueue(queueName); - populateDestination(10, destination, connection); - - MessageConsumer consumer = session.createConsumer(destination); - TextMessage msg = null; - for (int i = 0; i < 5; i++) { - msg = (TextMessage) consumer.receive(20000); - LOG.info("not redelivered? got: " + msg); - assertNotNull("got the message", msg); - assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); - assertEquals("not a redelivery", false, msg.getJMSRedelivered()); - } - session.rollback(); - consumer.close(); - - restartBroker(); - - // make failover aware of the restarted auto assigned port - connection.getTransport().narrow(FailoverTransport.class).add(true, broker.getTransportConnectors().get(0).getPublishableConnectString()); - - consumer = session.createConsumer(destination); - for (int i = 0; i < 5; i++) { - msg = (TextMessage) consumer.receive(4000); - LOG.info("redelivered? got: " + msg); - assertNotNull("got the message again", msg); - assertEquals("redelivery count survives restart", 2, msg.getLongProperty("JMSXDeliveryCount")); - assertEquals("re delivery flag", true, msg.getJMSRedelivered()); - } - session.commit(); - - // consume the rest that were not redeliveries - for (int i = 0; i < 5; i++) { - msg = (TextMessage) consumer.receive(20000); - LOG.info("not redelivered? got: " + msg); - assertNotNull("got the message", msg); - assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); - assertEquals("not a redelivery", false, msg.getJMSRedelivered()); - } - session.commit(); - - connection.close(); - } - - @org.junit.Test - public void testValidateRedeliveryFlagAfterRecovery() throws Exception { - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() + "?jms.prefetchPolicy.all=0"); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Destination destination = session.createQueue(queueName); - populateDestination(1, destination, connection); - - MessageConsumer consumer = session.createConsumer(destination); - TextMessage msg = (TextMessage) consumer.receive(5000); - LOG.info("got: " + msg); - assertNotNull("got the message", msg); - assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); - assertEquals("not a redelivery", false, msg.getJMSRedelivered()); - - stopBrokerWithStoreFailure(broker, persistenceAdapterChoice); - - broker = createRestartedBroker(); - broker.start(); - - connection.close(); - - connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - - session = connection.createSession(true, Session.SESSION_TRANSACTED); - consumer = session.createConsumer(destination); - msg = (TextMessage) consumer.receive(10000); - assertNotNull("got the message again", msg); - assertEquals("redelivery count survives restart", 2, msg.getLongProperty("JMSXDeliveryCount")); - assertEquals("re delivery flag", true, msg.getJMSRedelivered()); - - session.commit(); - connection.close(); - } - - private void restartBroker() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - broker = createRestartedBroker(); - broker.start(); - } - - private BrokerService createRestartedBroker() throws Exception { - broker = new BrokerService(); - configureBroker(broker); - return broker; - } - - private void populateDestination(final int nbMessages, - final Destination destination, - javax.jms.Connection connection) throws JMSException { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - for (int i = 1; i <= nbMessages; i++) { - producer.send(session.createTextMessage("")); - } - producer.close(); - session.close(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RedeliveryRestartWithExceptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RedeliveryRestartWithExceptionTest.java deleted file mode 100644 index 7930b2266a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/RedeliveryRestartWithExceptionTest.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.activemq.broker; - -import javax.jms.ConnectionFactory; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.io.File; -import java.io.IOException; -import java.util.Set; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.TestSupport; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.broker.scheduler.JobSchedulerStore; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.command.Message; -import org.apache.activemq.command.ProducerId; -import org.apache.activemq.store.MessageStore; -import org.apache.activemq.store.PersistenceAdapter; -import org.apache.activemq.store.ProxyMessageStore; -import org.apache.activemq.store.ProxyTopicMessageStore; -import org.apache.activemq.store.TopicMessageStore; -import org.apache.activemq.store.TransactionStore; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.transport.tcp.TcpTransport; -import org.apache.activemq.usage.SystemUsage; -import org.junit.After; -import org.junit.Before; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class RedeliveryRestartWithExceptionTest extends TestSupport { - - private static final transient Logger LOG = LoggerFactory.getLogger(RedeliveryRestartWithExceptionTest.class); - ActiveMQConnection connection; - BrokerService broker = null; - String queueName = "redeliveryRestartQ"; - - @Override - @Before - public void setUp() throws Exception { - super.setUp(); - broker = new BrokerService(); - configureBroker(broker, true); - broker.setDeleteAllMessagesOnStartup(true); - broker.start(); - } - - @Override - @After - public void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - broker.stop(); - super.tearDown(); - } - - protected void configureBroker(BrokerService broker, boolean throwExceptionOnUpdate) throws Exception { - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policy = new PolicyEntry(); - policy.setPersistJMSRedelivered(true); - policyMap.setDefaultEntry(policy); - broker.setDestinationPolicy(policyMap); - broker.setPersistenceAdapter(new KahaDBWithUpdateExceptionPersistenceAdapter(throwExceptionOnUpdate)); - broker.addConnector("tcp://0.0.0.0:0"); - } - - @org.junit.Test - public void testValidateRedeliveryFlagAfterRestart() throws Exception { - - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() + "?jms.prefetchPolicy.all=0"); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Destination destination = session.createQueue(queueName); - populateDestination(10, destination, connection, true); - TextMessage msg = null; - MessageConsumer consumer = session.createConsumer(destination); - Exception expectedException = null; - try { - for (int i = 0; i < 5; i++) { - msg = (TextMessage) consumer.receive(5000); - LOG.info("not redelivered? got: " + msg); - assertNotNull("got the message", msg); - assertTrue("Should not receive the 5th message", i < 4); - //The first 4 messages will be ok but the 5th one should hit an exception in updateMessage and should not be delivered - } - } catch (Exception e) { - //Expecting an exception and disconnect on the 5th message - LOG.info("Got expected:", e); - expectedException = e; - } - assertNotNull("Expecting an exception when updateMessage fails", expectedException); - - consumer.close(); - connection.close(); - - restartBroker(); - - connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() + "?jms.prefetchPolicy.all=0"); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - destination = session.createQueue(queueName); - consumer = session.createConsumer(destination); - - // consume the messages that were previously delivered - for (int i = 0; i < 4; i++) { - msg = (TextMessage) consumer.receive(4000); - LOG.info("redelivered? got: " + msg); - assertNotNull("got the message again", msg); - assertEquals("re delivery flag", true, msg.getJMSRedelivered()); - assertTrue("redelivery count survives restart", msg.getLongProperty("JMSXDeliveryCount") > 1); - msg.acknowledge(); - } - - // consume the rest that were not redeliveries - for (int i = 0; i < 6; i++) { - msg = (TextMessage) consumer.receive(4000); - LOG.info("not redelivered? got: " + msg); - assertNotNull("got the message", msg); - assertEquals("not a redelivery", false, msg.getJMSRedelivered()); - assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); - msg.acknowledge(); - } - connection.close(); - } - - @org.junit.Test - public void testValidateRedeliveryFlagAfterTransientFailureConnectionDrop() throws Exception { - - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() + "?jms.prefetchPolicy.all=0"); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Destination destination = session.createQueue(queueName); - populateDestination(10, destination, connection, true); - TextMessage msg = null; - MessageConsumer consumer = session.createConsumer(destination); - Exception expectedException = null; - try { - for (int i = 0; i < 5; i++) { - msg = (TextMessage) consumer.receive(5000); - LOG.info("not redelivered? got: " + msg); - assertNotNull("got the message", msg); - assertTrue("Should not receive the 5th message", i < 4); - //The first 4 messages will be ok but the 5th one should hit an exception in updateMessage and should not be delivered - } - } catch (Exception e) { - //Expecting an exception and disconnect on the 5th message - LOG.info("Got expected:", e); - expectedException = e; - } - assertNotNull("Expecting an exception when updateMessage fails", expectedException); - - consumer.close(); - connection.close(); - - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - destination = session.createQueue(queueName); - consumer = session.createConsumer(destination); - - // consume the messages that were previously delivered - for (int i = 0; i < 4; i++) { - msg = (TextMessage) consumer.receive(4000); - LOG.info("redelivered? got: " + msg); - assertNotNull("got the message again", msg); - assertEquals("re delivery flag on:" + i, true, msg.getJMSRedelivered()); - assertTrue("redelivery count survives reconnect for:" + i, msg.getLongProperty("JMSXDeliveryCount") > 1); - msg.acknowledge(); - } - - // consume the rest that were not redeliveries - for (int i = 0; i < 6; i++) { - msg = (TextMessage) consumer.receive(4000); - LOG.info("not redelivered? got: " + msg); - assertNotNull("got the message", msg); - assertEquals("not a redelivery", false, msg.getJMSRedelivered()); - assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); - msg.acknowledge(); - } - connection.close(); - } - - @org.junit.Test - public void testValidateRedeliveryFlagOnNonPersistentAfterTransientFailureConnectionDrop() throws Exception { - - ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() + "?jms.prefetchPolicy.all=0"); - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Destination destination = session.createQueue(queueName); - populateDestination(10, destination, connection, false); - TextMessage msg = null; - MessageConsumer consumer = session.createConsumer(destination); - for (int i = 0; i < 5; i++) { - msg = (TextMessage) consumer.receive(5000); - assertNotNull("got the message", msg); - assertFalse("not redelivered", msg.getJMSRedelivered()); - } - - connection.getTransport().narrow(TcpTransport.class).getTransportListener().onException(new IOException("Die")); - - connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.start(); - - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - destination = session.createQueue(queueName); - consumer = session.createConsumer(destination); - - // consume the messages that were previously delivered - for (int i = 0; i < 5; i++) { - msg = (TextMessage) consumer.receive(4000); - LOG.info("redelivered? got: " + msg); - assertNotNull("got the message again", msg); - assertEquals("redelivery flag set on:" + i, true, msg.getJMSRedelivered()); - assertTrue("redelivery count survives reconnect for:" + i, msg.getLongProperty("JMSXDeliveryCount") > 1); - msg.acknowledge(); - } - - // consume the rest that were not redeliveries - for (int i = 0; i < 5; i++) { - msg = (TextMessage) consumer.receive(4000); - LOG.info("not redelivered? got: " + msg); - assertNotNull("got the message", msg); - assertEquals("not a redelivery", false, msg.getJMSRedelivered()); - assertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount")); - msg.acknowledge(); - } - connection.close(); - } - - private void restartBroker() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - broker = createRestartedBroker(); - broker.start(); - } - - private BrokerService createRestartedBroker() throws Exception { - broker = new BrokerService(); - configureBroker(broker, false); - return broker; - } - - private void populateDestination(final int nbMessages, - final Destination destination, - javax.jms.Connection connection, - boolean persistent) throws JMSException { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); - for (int i = 1; i <= nbMessages; i++) { - producer.send(session.createTextMessage("")); - } - producer.close(); - session.close(); - } - - private class KahaDBWithUpdateExceptionPersistenceAdapter implements PersistenceAdapter { - - private KahaDBPersistenceAdapter kahaDB = new KahaDBPersistenceAdapter(); - private boolean throwExceptionOnUpdate; - - public KahaDBWithUpdateExceptionPersistenceAdapter(boolean throwExceptionOnUpdate) { - this.throwExceptionOnUpdate = throwExceptionOnUpdate; - } - - @Override - public void start() throws Exception { - kahaDB.start(); - } - - @Override - public void stop() throws Exception { - kahaDB.stop(); - } - - @Override - public Set getDestinations() { - return kahaDB.getDestinations(); - } - - @Override - public MessageStore createQueueMessageStore(ActiveMQQueue destination) throws IOException { - MessageStore proxyMessageStoreWithException = new ProxyMessageStoreWithUpdateException(kahaDB.createQueueMessageStore(destination), throwExceptionOnUpdate); - return proxyMessageStoreWithException; - } - - @Override - public TopicMessageStore createTopicMessageStore(ActiveMQTopic destination) throws IOException { - TopicMessageStore proxyMessageStoreWithException = new ProxyTopicMessageStoreWithUpdateException(kahaDB.createTopicMessageStore(destination), throwExceptionOnUpdate); - return proxyMessageStoreWithException; - } - - @Override - public JobSchedulerStore createJobSchedulerStore() throws IOException, UnsupportedOperationException { - return kahaDB.createJobSchedulerStore(); - } - - @Override - public void removeQueueMessageStore(ActiveMQQueue destination) { - kahaDB.removeQueueMessageStore(destination); - } - - @Override - public void removeTopicMessageStore(ActiveMQTopic destination) { - kahaDB.removeTopicMessageStore(destination); - } - - @Override - public TransactionStore createTransactionStore() throws IOException { - return kahaDB.createTransactionStore(); - } - - @Override - public void beginTransaction(ConnectionContext context) throws IOException { - kahaDB.beginTransaction(context); - } - - @Override - public void commitTransaction(ConnectionContext context) throws IOException { - kahaDB.commitTransaction(context); - } - - @Override - public void rollbackTransaction(ConnectionContext context) throws IOException { - kahaDB.rollbackTransaction(context); - } - - @Override - public long getLastMessageBrokerSequenceId() throws IOException { - return kahaDB.getLastMessageBrokerSequenceId(); - } - - @Override - public void deleteAllMessages() throws IOException { - kahaDB.deleteAllMessages(); - } - - @Override - public void setUsageManager(SystemUsage usageManager) { - kahaDB.setUsageManager(usageManager); - } - - @Override - public void setBrokerName(String brokerName) { - kahaDB.setBrokerName(brokerName); - } - - @Override - public void setDirectory(File dir) { - kahaDB.setDirectory(dir); - } - - @Override - public File getDirectory() { - return kahaDB.getDirectory(); - } - - @Override - public void checkpoint(boolean sync) throws IOException { - kahaDB.checkpoint(sync); - } - - @Override - public long size() { - return kahaDB.size(); - } - - @Override - public long getLastProducerSequenceId(ProducerId id) throws IOException { - return kahaDB.getLastProducerSequenceId(id); - } - - @Override - public void allowIOResumption() { - kahaDB.allowIOResumption(); - } - } - - private class ProxyMessageStoreWithUpdateException extends ProxyMessageStore { - - private boolean throwExceptionOnUpdate; - private int numBeforeException = 4; - - public ProxyMessageStoreWithUpdateException(MessageStore delegate, boolean throwExceptionOnUpdate) { - super(delegate); - this.throwExceptionOnUpdate = throwExceptionOnUpdate; - } - - @Override - public void updateMessage(Message message) throws IOException { - if (throwExceptionOnUpdate) { - if (numBeforeException > 0) { - numBeforeException--; - super.updateMessage(message); - } else { - // lets only do it once so we can validate transient store failure - throwExceptionOnUpdate = false; - - //A message that has never been delivered will hit this exception - throw new IOException("Hit our simulated exception writing the update to disk"); - } - } else { - super.updateMessage(message); - } - } - } - - private class ProxyTopicMessageStoreWithUpdateException extends ProxyTopicMessageStore { - - private boolean throwExceptionOnUpdate; - private int numBeforeException = 4; - - public ProxyTopicMessageStoreWithUpdateException(TopicMessageStore delegate, boolean throwExceptionOnUpdate) { - super(delegate); - this.throwExceptionOnUpdate = throwExceptionOnUpdate; - } - - @Override - public void updateMessage(Message message) throws IOException { - if (throwExceptionOnUpdate) { - if (numBeforeException > 0) { - numBeforeException--; - super.updateMessage(message); - } else { - //A message that has never been delivered will hit this exception - throw new IOException("Hit our simulated exception writing the update to disk"); - } - } else { - super.updateMessage(message); - } - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/SpringTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/SpringTest.java deleted file mode 100644 index 3ca1e3f88b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/SpringTest.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.activemq.broker; - -import javax.jms.Message; -import java.io.File; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.activemq.spring.SpringConsumer; -import org.apache.activemq.spring.SpringProducer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.support.AbstractApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class SpringTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(SpringTest.class); - - protected AbstractApplicationContext context; - protected SpringConsumer consumer; - protected SpringProducer producer; - - public void testSenderWithSpringXml() throws Exception { - assertSenderConfig("org/apache/activemq/broker/spring.xml"); - } - - /** - * assert method that is used by all the test method to send and receive messages - * based on each spring configuration. - * - * @param config - * @throws Exception - */ - protected void assertSenderConfig(String config) throws Exception { - context = new ClassPathXmlApplicationContext(config); - - consumer = (SpringConsumer) context.getBean("consumer"); - assertTrue("Found a valid consumer", consumer != null); - - consumer.start(); - - producer = (SpringProducer) context.getBean("producer"); - assertTrue("Found a valid producer", producer != null); - - consumer.flushMessages(); - producer.start(); - - // lets sleep a little to give the JMS time to dispatch stuff - consumer.waitForMessagesToArrive(producer.getMessageCount()); - - // now lets check that the consumer has received some messages - List messages = consumer.flushMessages(); - LOG.info("Consumer has received messages...."); - for (Message message : messages) { - LOG.info("Received: " + message); - } - - assertEquals("Message count", producer.getMessageCount(), messages.size()); - } - - /** - * Clean up method. - * - * @throws Exception - */ - @Override - protected void tearDown() throws Exception { - if (consumer != null) { - consumer.stop(); - } - if (producer != null) { - producer.stop(); - } - - if (context != null) { - context.destroy(); - } - } - - @Override - protected void setUp() throws Exception { - if (System.getProperty("basedir") == null) { - File file = new File("."); - System.setProperty("basedir", file.getAbsolutePath()); - } - super.setUp(); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/TopicSubscriptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/TopicSubscriptionTest.java deleted file mode 100644 index 98ccbc5615..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/TopicSubscriptionTest.java +++ /dev/null @@ -1,163 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker; - -import org.apache.activemq.util.ThreadTracker; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.BlockJUnit4ClassRunner; - -@RunWith(BlockJUnit4ClassRunner.class) -public class TopicSubscriptionTest extends QueueSubscriptionTest { - - @Override - @Before - public void setUp() throws Exception { - super.setUp(); - durable = true; - topic = true; - } - - @Override - @After - public void tearDown() throws Exception { - super.tearDown(); - ThreadTracker.result(); - } - - @Override - @Test(timeout = 60 * 1000) - public void testManyProducersManyConsumers() throws Exception { - consumerCount = 40; - producerCount = 20; - messageCount = 100; - messageSize = 1; - prefetchCount = 10; - - doMultipleClientsTest(); - - assertTotalMessagesReceived(messageCount * producerCount * consumerCount); - assertDestinationMemoryUsageGoesToZero(); - } - - @Override - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersLargeMessagesOnePrefetch() throws Exception { - consumerCount = 2; - producerCount = 1; - messageCount = 10; - messageSize = 1024 * 1024 * 1; // 1 MB - prefetchCount = 1; - - doMultipleClientsTest(); - - assertTotalMessagesReceived(messageCount * consumerCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } - - @Override - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersSmallMessagesOnePrefetch() throws Exception { - consumerCount = 2; - producerCount = 1; - prefetchCount = 1; - messageSize = 1024; - messageCount = 1000; - - doMultipleClientsTest(); - - assertTotalMessagesReceived(messageCount * consumerCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } - - @Override - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersSmallMessagesLargePrefetch() throws Exception { - consumerCount = 2; - producerCount = 1; - messageCount = 1000; - messageSize = 1024; - prefetchCount = messageCount * 2; - - doMultipleClientsTest(); - - assertTotalMessagesReceived(messageCount * consumerCount * producerCount); - } - - @Override - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersLargeMessagesLargePrefetch() throws Exception { - consumerCount = 2; - producerCount = 1; - messageCount = 10; - messageSize = 1024 * 1024 * 1; // 1 MB - prefetchCount = messageCount * 2; - - doMultipleClientsTest(); - - assertTotalMessagesReceived(messageCount * consumerCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } - - @Override - @Test(timeout = 60 * 1000) - public void testOneProducerManyConsumersFewMessages() throws Exception { - consumerCount = 50; - producerCount = 1; - messageCount = 10; - messageSize = 1; // 1 byte - prefetchCount = 10; - - doMultipleClientsTest(); - - assertTotalMessagesReceived(messageCount * consumerCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } - - @Override - @Test(timeout = 60 * 1000) - public void testOneProducerManyConsumersManyMessages() throws Exception { - consumerCount = 50; - producerCount = 1; - messageCount = 100; - messageSize = 1; // 1 byte - prefetchCount = 10; - - doMultipleClientsTest(); - - assertTotalMessagesReceived(messageCount * consumerCount * producerCount); - assertDestinationMemoryUsageGoesToZero(); - } - - @Override - @Test(timeout = 60 * 1000) - public void testManyProducersOneConsumer() throws Exception { - consumerCount = 1; - producerCount = 20; - messageCount = 100; - messageSize = 1; // 1 byte - prefetchCount = 10; - - doMultipleClientsTest(); - - assertTotalMessagesReceived(messageCount * producerCount * consumerCount); - assertDestinationMemoryUsageGoesToZero(); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/XARecoveryBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/XARecoveryBrokerTest.java deleted file mode 100644 index 344dba8f91..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/XARecoveryBrokerTest.java +++ /dev/null @@ -1,1251 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker; - -import javax.jms.JMSException; -import javax.management.InstanceNotFoundException; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -import junit.framework.Test; - -import org.apache.activemq.broker.jmx.BrokerMBeanSupport; -import org.apache.activemq.broker.jmx.DestinationViewMBean; -import org.apache.activemq.broker.jmx.PersistenceAdapterViewMBean; -import org.apache.activemq.broker.jmx.RecoveredXATransactionViewMBean; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.SharedDeadLetterStrategy; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.command.ConnectionInfo; -import org.apache.activemq.command.ConsumerInfo; -import org.apache.activemq.command.DataArrayResponse; -import org.apache.activemq.command.Message; -import org.apache.activemq.command.MessageAck; -import org.apache.activemq.command.ProducerInfo; -import org.apache.activemq.command.Response; -import org.apache.activemq.command.SessionInfo; -import org.apache.activemq.command.TransactionId; -import org.apache.activemq.command.TransactionInfo; -import org.apache.activemq.command.XATransactionId; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.util.JMXSupport; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Used to simulate the recovery that occurs when a broker shuts down. - */ -public class XARecoveryBrokerTest extends BrokerRestartTestSupport { - - protected static final Logger LOG = LoggerFactory.getLogger(XARecoveryBrokerTest.class); - public boolean prioritySupport = false; - - public void testPreparedJmxView() throws Exception { - - ActiveMQDestination destination = createDestination(); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // Prepare 4 message sends. - for (int i = 0; i < 4; i++) { - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - message.setTransactionId(txid); - connection.send(message); - - // Prepare - connection.send(createPrepareTransaction(connectionInfo, txid)); - } - - Response response = connection.request(new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER)); - assertNotNull(response); - DataArrayResponse dar = (DataArrayResponse) response; - assertEquals(4, dar.getData().length); - - // view prepared in kahadb view - if (broker.getPersistenceAdapter() instanceof KahaDBPersistenceAdapter) { - PersistenceAdapterViewMBean kahadbView = getProxyToPersistenceAdapter(broker.getPersistenceAdapter().toString()); - String txFromView = kahadbView.getTransactions(); - LOG.info("Tx view fromm PA:" + txFromView); - assertTrue("xid with our dud format in transaction string " + txFromView, txFromView.contains("XID:[55,")); - } - - // restart the broker. - restartBroker(); - - connection = createConnection(); - connectionInfo = createConnectionInfo(); - connection.send(connectionInfo); - - response = connection.request(new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER)); - assertNotNull(response); - dar = (DataArrayResponse) response; - assertEquals(4, dar.getData().length); - - // validate destination depth via jmx - DestinationViewMBean destinationView = getProxyToDestination(destinationList(destination)[0]); - assertEquals("enqueue count does not see prepared", 0, destinationView.getQueueSize()); - - TransactionId first = (TransactionId) dar.getData()[0]; - int commitCount = 0; - // via jmx, force outcome - for (int i = 0; i < 4; i++) { - RecoveredXATransactionViewMBean mbean = getProxyToPreparedTransactionViewMBean((TransactionId) dar.getData()[i]); - if (i % 2 == 0) { - mbean.heuristicCommit(); - commitCount++; - } else { - mbean.heuristicRollback(); - } - } - - // verify all completed - response = connection.request(new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER)); - assertNotNull(response); - dar = (DataArrayResponse) response; - assertEquals(0, dar.getData().length); - - // verify messages available - assertEquals("enqueue count reflects outcome", commitCount, destinationView.getQueueSize()); - - // verify mbeans gone - try { - RecoveredXATransactionViewMBean gone = getProxyToPreparedTransactionViewMBean(first); - gone.heuristicRollback(); - fail("Excepted not found"); - } catch (InstanceNotFoundException expectedNotfound) { - } - } - - private PersistenceAdapterViewMBean getProxyToPersistenceAdapter(String name) throws MalformedObjectNameException, JMSException { - return (PersistenceAdapterViewMBean) broker.getManagementContext().newProxyInstance(BrokerMBeanSupport.createPersistenceAdapterName(broker.getBrokerObjectName().toString(), name), PersistenceAdapterViewMBean.class, true); - } - - private RecoveredXATransactionViewMBean getProxyToPreparedTransactionViewMBean(TransactionId xid) throws MalformedObjectNameException, JMSException { - - ObjectName objectName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,transactionType=RecoveredXaTransaction,xid=" + JMXSupport.encodeObjectNamePart(xid.toString())); - RecoveredXATransactionViewMBean proxy = (RecoveredXATransactionViewMBean) broker.getManagementContext().newProxyInstance(objectName, RecoveredXATransactionViewMBean.class, true); - return proxy; - } - - private DestinationViewMBean getProxyToDestination(ActiveMQDestination destination) throws MalformedObjectNameException, JMSException { - - final ObjectName objectName = new ObjectName("org.apache.activemq:type=Broker,brokerName=" + broker.getBrokerName() + ",destinationType=" + JMXSupport.encodeObjectNamePart(destination.getDestinationTypeAsString()) + ",destinationName=" + JMXSupport.encodeObjectNamePart(destination.getPhysicalName())); - - DestinationViewMBean proxy = (DestinationViewMBean) broker.getManagementContext().newProxyInstance(objectName, DestinationViewMBean.class, true); - return proxy; - - } - - public void testPreparedTransactionRecoveredOnRestart() throws Exception { - - ActiveMQDestination destination = createDestination(); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // Prepare 4 message sends. - for (int i = 0; i < 4; i++) { - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - message.setTransactionId(txid); - connection.send(message); - - // Prepare - connection.send(createPrepareTransaction(connectionInfo, txid)); - } - - // Since prepared but not committed.. they should not get delivered. - assertNull(receiveMessage(connection)); - assertNoMessagesLeft(connection); - connection.request(closeConnectionInfo(connectionInfo)); - - // restart the broker. - restartBroker(); - - // Setup the consumer and try receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // Since prepared but not committed.. they should not get delivered. - assertNull(receiveMessage(connection)); - assertNoMessagesLeft(connection); - - Response response = connection.request(new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER)); - assertNotNull(response); - DataArrayResponse dar = (DataArrayResponse) response; - assertEquals(4, dar.getData().length); - - // ensure we can close a connection with prepared transactions - connection.request(closeConnectionInfo(connectionInfo)); - - // open again to deliver outcome - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // Commit the prepared transactions. - for (int i = 0; i < dar.getData().length; i++) { - TransactionId transactionId = (TransactionId) dar.getData()[i]; - LOG.info("commit: " + transactionId); - connection.request(createCommitTransaction2Phase(connectionInfo, transactionId)); - } - - // We should get the committed transactions. - final int countToReceive = expectedMessageCount(4, destination); - for (int i = 0; i < countToReceive; i++) { - Message m = receiveMessage(connection, TimeUnit.SECONDS.toMillis(10)); - LOG.info("received: " + m); - assertNotNull("Got non null message: " + i, m); - } - - assertNoMessagesLeft(connection); - assertEmptyDLQ(); - } - - private void assertEmptyDLQ() throws Exception { - try { - DestinationViewMBean destinationView = getProxyToDestination(new ActiveMQQueue(SharedDeadLetterStrategy.DEFAULT_DEAD_LETTER_QUEUE_NAME)); - assertEquals("nothing on dlq", 0, destinationView.getQueueSize()); - assertEquals("nothing added to dlq", 0, destinationView.getEnqueueCount()); - } catch (java.lang.reflect.UndeclaredThrowableException maybeOk) { - if (maybeOk.getUndeclaredThrowable() instanceof javax.management.InstanceNotFoundException) { - // perfect no dlq - } else { - throw maybeOk; - } - } - } - - public void testPreparedInterleavedTransactionRecoveredOnRestart() throws Exception { - - ActiveMQDestination destination = createDestination(); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // Prepare 4 message sends. - for (int i = 0; i < 4; i++) { - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - message.setTransactionId(txid); - connection.send(message); - - // Prepare - connection.send(createPrepareTransaction(connectionInfo, txid)); - } - - // Since prepared but not committed.. they should not get delivered. - assertNull(receiveMessage(connection)); - assertNoMessagesLeft(connection); - - // send non tx message - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.request(message); - - connection.request(closeConnectionInfo(connectionInfo)); - - // restart the broker. - restartBroker(); - - // Setup the consumer and try receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // consume non transacted message, but don't ack - int countToReceive = expectedMessageCount(1, destination); - for (int i = 0; i < countToReceive; i++) { - Message m = receiveMessage(connection, TimeUnit.SECONDS.toMillis(10)); - LOG.info("received: " + m); - assertNotNull("got non tx message after prepared", m); - } - - // Since prepared but not committed.. they should not get delivered. - assertNull(receiveMessage(connection)); - assertNoMessagesLeft(connection); - - Response response = connection.request(new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER)); - assertNotNull(response); - DataArrayResponse dar = (DataArrayResponse) response; - assertEquals(4, dar.getData().length); - - // ensure we can close a connection with prepared transactions - connection.request(closeConnectionInfo(connectionInfo)); - - // open again to deliver outcome - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - - // Commit the prepared transactions. - for (int i = 0; i < dar.getData().length; i++) { - TransactionId transactionId = (TransactionId) dar.getData()[i]; - LOG.info("commit: " + transactionId); - connection.request(createCommitTransaction2Phase(connectionInfo, transactionId)); - } - - consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // We should get the committed transactions and the non tx message - countToReceive = expectedMessageCount(5, destination); - for (int i = 0; i < countToReceive; i++) { - Message m = receiveMessage(connection, TimeUnit.SECONDS.toMillis(10)); - LOG.info("received: " + m); - assertNotNull("Got non null message: " + i, m); - } - - assertNoMessagesLeft(connection); - assertEmptyDLQ(); - } - - public void testTopicPreparedTransactionRecoveredOnRestart() throws Exception { - ActiveMQDestination destination = new ActiveMQTopic("TryTopic"); - - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - connectionInfo.setClientId("durable"); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setSubscriptionName("durable"); - connection.send(consumerInfo); - - // Prepare 4 message sends. - for (int i = 0; i < 4; i++) { - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - message.setTransactionId(txid); - connection.send(message); - - // Prepare - connection.send(createPrepareTransaction(connectionInfo, txid)); - } - - // Since prepared but not committed.. they should not get delivered. - assertNull(receiveMessage(connection)); - assertNoMessagesLeft(connection); - connection.request(closeConnectionInfo(connectionInfo)); - - // restart the broker. - restartBroker(); - - // Setup the consumer and try receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - connectionInfo.setClientId("durable"); - - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setSubscriptionName("durable"); - connection.send(consumerInfo); - - // Since prepared but not committed.. they should not get delivered. - assertNull(receiveMessage(connection)); - assertNoMessagesLeft(connection); - - Response response = connection.request(new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER)); - assertNotNull(response); - DataArrayResponse dar = (DataArrayResponse) response; - assertEquals(4, dar.getData().length); - - // ensure we can close a connection with prepared transactions - connection.request(closeConnectionInfo(connectionInfo)); - - // open again to deliver outcome - connection = createConnection(); - connectionInfo = createConnectionInfo(); - connectionInfo.setClientId("durable"); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setSubscriptionName("durable"); - connection.send(consumerInfo); - - // Commit the prepared transactions. - for (int i = 0; i < dar.getData().length; i++) { - connection.request(createCommitTransaction2Phase(connectionInfo, (TransactionId) dar.getData()[i])); - } - - // We should get the committed transactions. - for (int i = 0; i < expectedMessageCount(4, destination); i++) { - Message m = receiveMessage(connection, TimeUnit.SECONDS.toMillis(10)); - assertNotNull(m); - } - - assertNoMessagesLeft(connection); - - } - - public void testQueuePersistentCommittedMessagesNotLostOnRestart() throws Exception { - - ActiveMQDestination destination = createDestination(); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - message.setTransactionId(txid); - connection.send(message); - } - - // Commit - connection.send(createCommitTransaction1Phase(connectionInfo, txid)); - connection.request(closeConnectionInfo(connectionInfo)); - // restart the broker. - restartBroker(); - - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - for (int i = 0; i < expectedMessageCount(4, destination); i++) { - Message m = receiveMessage(connection); - assertNotNull(m); - } - - assertNoMessagesLeft(connection); - } - - public void testQueuePersistentCommitted2PhaseMessagesNotLostOnRestart() throws Exception { - - ActiveMQDestination destination = createDestination(); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - message.setTransactionId(txid); - connection.send(message); - } - - // Commit 2 phase - connection.request(createPrepareTransaction(connectionInfo, txid)); - connection.send(createCommitTransaction2Phase(connectionInfo, txid)); - - connection.request(closeConnectionInfo(connectionInfo)); - // restart the broker. - restartBroker(); - - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - for (int i = 0; i < expectedMessageCount(4, destination); i++) { - Message m = receiveMessage(connection); - assertNotNull(m); - } - - assertNoMessagesLeft(connection); - } - - public void testQueuePersistentCommittedAcksNotLostOnRestart() throws Exception { - - ActiveMQDestination destination = createDestination(); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } - - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - ConsumerInfo consumerInfo; - Message m = null; - for (ActiveMQDestination dest : destinationList(destination)) { - // Setup the consumer and receive the message. - consumerInfo = createConsumerInfo(sessionInfo, dest); - connection.send(consumerInfo); - - for (int i = 0; i < 4; i++) { - m = receiveMessage(connection); - assertNotNull(m); - } - - MessageAck ack = createAck(consumerInfo, m, 4, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - } - - // Commit - connection.request(createCommitTransaction1Phase(connectionInfo, txid)); - - // restart the broker. - restartBroker(); - - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // No messages should be delivered. - assertNoMessagesLeft(connection); - - m = receiveMessage(connection); - assertNull(m); - } - - public void testQueuePersistentPreparedAcksNotLostOnRestart() throws Exception { - - ActiveMQDestination destination = createDestination(); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } - - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - ConsumerInfo consumerInfo; - Message m = null; - for (ActiveMQDestination dest : destinationList(destination)) { - // Setup the consumer and receive the message. - consumerInfo = createConsumerInfo(sessionInfo, dest); - connection.send(consumerInfo); - - for (int i = 0; i < 4; i++) { - m = receiveMessage(connection); - assertNotNull(m); - } - - // one ack with last received, mimic a beforeEnd synchronization - MessageAck ack = createAck(consumerInfo, m, 4, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - } - - connection.request(createPrepareTransaction(connectionInfo, txid)); - - // restart the broker. - restartBroker(); - - connection = createConnection(); - connectionInfo = createConnectionInfo(); - connection.send(connectionInfo); - - // validate recovery - TransactionInfo recoverInfo = new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER); - DataArrayResponse dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); - - assertEquals("there is a prepared tx", 1, dataArrayResponse.getData().length); - assertEquals("it matches", txid, dataArrayResponse.getData()[0]); - - sessionInfo = createSessionInfo(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // no redelivery, exactly once semantics unless there is rollback - m = receiveMessage(connection); - assertNull(m); - assertNoMessagesLeft(connection); - - // validate destination depth via jmx - DestinationViewMBean destinationView = getProxyToDestination(destinationList(destination)[0]); - assertEquals("enqueue count does not see prepared acks", 4, destinationView.getQueueSize()); - assertEquals("enqueue count does not see prepared acks", 0, destinationView.getDequeueCount()); - - connection.request(createCommitTransaction2Phase(connectionInfo, txid)); - - // validate recovery complete - dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); - assertEquals("there are no prepared tx", 0, dataArrayResponse.getData().length); - - assertEquals("enqueue count does not see committed acks", 0, destinationView.getQueueSize()); - assertEquals("enqueue count does not see committed acks", 4, destinationView.getDequeueCount()); - - } - - public void initCombosForTestTopicPersistentPreparedAcksNotLostOnRestart() { - addCombinationValues("prioritySupport", new Boolean[]{Boolean.FALSE, Boolean.TRUE}); - } - - public void testTopicPersistentPreparedAcksNotLostOnRestart() throws Exception { - ActiveMQDestination destination = new ActiveMQTopic("TryTopic"); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - connectionInfo.setClientId("durable"); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - // setup durable subs - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setSubscriptionName("durable"); - connection.send(consumerInfo); - - final int numMessages = 4; - for (int i = 0; i < numMessages; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } - - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - final int messageCount = expectedMessageCount(numMessages, destination); - Message m = null; - for (int i = 0; i < messageCount; i++) { - m = receiveMessage(connection); - assertNotNull("unexpected null on: " + i, m); - } - - // one ack with last received, mimic a beforeEnd synchronization - MessageAck ack = createAck(consumerInfo, m, messageCount, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - - connection.request(createPrepareTransaction(connectionInfo, txid)); - - // restart the broker. - restartBroker(); - - connection = createConnection(); - connectionInfo = createConnectionInfo(); - connectionInfo.setClientId("durable"); - connection.send(connectionInfo); - - // validate recovery - TransactionInfo recoverInfo = new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER); - DataArrayResponse dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); - - assertEquals("there is a prepared tx", 1, dataArrayResponse.getData().length); - assertEquals("it matches", txid, dataArrayResponse.getData()[0]); - - sessionInfo = createSessionInfo(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setSubscriptionName("durable"); - connection.send(consumerInfo); - - // no redelivery, exactly once semantics unless there is rollback - m = receiveMessage(connection); - assertNull(m); - assertNoMessagesLeft(connection); - - connection.request(createCommitTransaction2Phase(connectionInfo, txid)); - - // validate recovery complete - dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); - assertEquals("there are no prepared tx", 0, dataArrayResponse.getData().length); - } - - public void testQueuePersistentPreparedAcksAvailableAfterRestartAndRollback() throws Exception { - - ActiveMQDestination destination = createDestination(); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - int numMessages = 4; - for (int i = 0; i < numMessages; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } - - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - ConsumerInfo consumerInfo; - Message message = null; - for (ActiveMQDestination dest : destinationList(destination)) { - // Setup the consumer and receive the message. - consumerInfo = createConsumerInfo(sessionInfo, dest); - connection.send(consumerInfo); - - for (int i = 0; i < numMessages; i++) { - message = receiveMessage(connection); - assertNotNull(message); - } - - // one ack with last received, mimic a beforeEnd synchronization - MessageAck ack = createAck(consumerInfo, message, numMessages, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - } - - connection.request(createPrepareTransaction(connectionInfo, txid)); - - // restart the broker. - restartBroker(); - - connection = createConnection(); - connectionInfo = createConnectionInfo(); - connection.send(connectionInfo); - - // validate recovery - TransactionInfo recoverInfo = new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER); - DataArrayResponse dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); - - assertEquals("there is a prepared tx", 1, dataArrayResponse.getData().length); - assertEquals("it matches", txid, dataArrayResponse.getData()[0]); - - sessionInfo = createSessionInfo(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - // no redelivery, exactly once semantics while prepared - message = receiveMessage(connection); - assertNull(message); - assertNoMessagesLeft(connection); - - // rollback so we get redelivery - connection.request(createRollbackTransaction(connectionInfo, txid)); - - LOG.info("new tx for redelivery"); - txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - for (ActiveMQDestination dest : destinationList(destination)) { - // Setup the consumer and receive the message. - consumerInfo = createConsumerInfo(sessionInfo, dest); - connection.send(consumerInfo); - - for (int i = 0; i < numMessages; i++) { - message = receiveMessage(connection); - assertNotNull("unexpected null on:" + i, message); - } - MessageAck ack = createAck(consumerInfo, message, numMessages, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - } - - // Commit - connection.request(createCommitTransaction1Phase(connectionInfo, txid)); - - // validate recovery complete - dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); - assertEquals("there are no prepared tx", 0, dataArrayResponse.getData().length); - } - - public void testQueuePersistentPreparedAcksAvailableAfterRollbackPrefetchOne() throws Exception { - - ActiveMQDestination destination = createDestination(); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - int numMessages = 1; - for (int i = 0; i < numMessages; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } - - final int messageCount = expectedMessageCount(numMessages, destination); - - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - // use consumer per destination for the composite dest case - // bc the same composite dest is used for sending so there - // will be duplicate message ids in the mix which a single - // consumer (PrefetchSubscription) cannot handle in a tx - // atm. The matching is based on messageId rather than messageId - // and destination - Set consumerInfos = new HashSet<>(); - for (ActiveMQDestination dest : destinationList(destination)) { - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, dest); - consumerInfo.setPrefetchSize(numMessages); - consumerInfos.add(consumerInfo); - } - - for (ConsumerInfo info : consumerInfos) { - connection.send(info); - } - - Message message = null; - for (ConsumerInfo info : consumerInfos) { - for (int i = 0; i < numMessages; i++) { - message = receiveMessage(connection); - assertNotNull(message); - connection.send(createAck(info, message, 1, MessageAck.DELIVERED_ACK_TYPE)); - } - MessageAck ack = createAck(info, message, numMessages, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - } - connection.request(createPrepareTransaction(connectionInfo, txid)); - - // reconnect - connection.send(connectionInfo.createRemoveCommand()); - connection = createConnection(); - connection.send(connectionInfo); - - // validate recovery - TransactionInfo recoverInfo = new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER); - DataArrayResponse dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); - - assertEquals("there is a prepared tx", 1, dataArrayResponse.getData().length); - assertEquals("it matches", txid, dataArrayResponse.getData()[0]); - - connection.send(sessionInfo); - - for (ConsumerInfo info : consumerInfos) { - connection.send(info); - } - - // no redelivery, exactly once semantics while prepared - message = receiveMessage(connection); - assertNull(message); - assertNoMessagesLeft(connection); - - // rollback so we get redelivery - connection.request(createRollbackTransaction(connectionInfo, txid)); - - LOG.info("new tx for redelivery"); - txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - for (ConsumerInfo info : consumerInfos) { - for (int i = 0; i < numMessages; i++) { - message = receiveMessage(connection); - assertNotNull("unexpected null on:" + i, message); - MessageAck ack = createAck(info, message, 1, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - } - } - - // Commit - connection.request(createCommitTransaction1Phase(connectionInfo, txid)); - - // validate recovery complete - dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); - assertEquals("there are no prepared tx", 0, dataArrayResponse.getData().length); - } - - public void initCombosForTestTopicPersistentPreparedAcksAvailableAfterRestartAndRollback() { - addCombinationValues("prioritySupport", new Boolean[]{Boolean.FALSE, Boolean.TRUE}); - } - - public void testTopicPersistentPreparedAcksAvailableAfterRestartAndRollback() throws Exception { - - ActiveMQDestination destination = new ActiveMQTopic("TryTopic"); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - connectionInfo.setClientId("durable"); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - // setup durable subs - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setSubscriptionName("durable"); - connection.send(consumerInfo); - - int numMessages = 4; - for (int i = 0; i < numMessages; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } - - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - Message message = null; - for (int i = 0; i < numMessages; i++) { - message = receiveMessage(connection); - assertNotNull(message); - } - - // one ack with last received, mimic a beforeEnd synchronization - MessageAck ack = createAck(consumerInfo, message, numMessages, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - - connection.request(createPrepareTransaction(connectionInfo, txid)); - - // restart the broker. - restartBroker(); - - connection = createConnection(); - connectionInfo = createConnectionInfo(); - connectionInfo.setClientId("durable"); - connection.send(connectionInfo); - - // validate recovery - TransactionInfo recoverInfo = new TransactionInfo(connectionInfo.getConnectionId(), null, TransactionInfo.RECOVER); - DataArrayResponse dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); - - assertEquals("there is a prepared tx", 1, dataArrayResponse.getData().length); - assertEquals("it matches", txid, dataArrayResponse.getData()[0]); - - sessionInfo = createSessionInfo(connectionInfo); - connection.send(sessionInfo); - consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setSubscriptionName("durable"); - connection.send(consumerInfo); - - // no redelivery, exactly once semantics while prepared - message = receiveMessage(connection); - assertNull(message); - assertNoMessagesLeft(connection); - - // rollback so we get redelivery - connection.request(createRollbackTransaction(connectionInfo, txid)); - - LOG.info("new tx for redelivery"); - txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - for (int i = 0; i < numMessages; i++) { - message = receiveMessage(connection); - assertNotNull("unexpected null on:" + i, message); - } - ack = createAck(consumerInfo, message, numMessages, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - - // Commit - connection.request(createCommitTransaction1Phase(connectionInfo, txid)); - - // validate recovery complete - dataArrayResponse = (DataArrayResponse) connection.request(recoverInfo); - assertEquals("there are no prepared tx", 0, dataArrayResponse.getData().length); - } - - public void initCombosForTestTopicPersistentPreparedAcksAvailableAfterRollback() { - addCombinationValues("prioritySupport", new Boolean[]{Boolean.FALSE, Boolean.TRUE}); - } - - public void testTopicPersistentPreparedAcksAvailableAfterRollback() throws Exception { - - ActiveMQDestination destination = new ActiveMQTopic("TryTopic"); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - connectionInfo.setClientId("durable"); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - // setup durable subs - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setSubscriptionName("durable"); - connection.send(consumerInfo); - - int numMessages = 4; - for (int i = 0; i < numMessages; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } - - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - Message message = null; - for (int i = 0; i < numMessages; i++) { - message = receiveMessage(connection); - assertNotNull(message); - } - - // one ack with last received, mimic a beforeEnd synchronization - MessageAck ack = createAck(consumerInfo, message, numMessages, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - - connection.request(createPrepareTransaction(connectionInfo, txid)); - - // rollback so we get redelivery - connection.request(createRollbackTransaction(connectionInfo, txid)); - - LOG.info("new consumer/tx for redelivery"); - connection.request(closeConnectionInfo(connectionInfo)); - - connectionInfo = createConnectionInfo(); - connectionInfo.setClientId("durable"); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - - // setup durable subs - consumerInfo = createConsumerInfo(sessionInfo, destination); - consumerInfo.setSubscriptionName("durable"); - connection.send(consumerInfo); - - txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - for (int i = 0; i < numMessages; i++) { - message = receiveMessage(connection); - assertNotNull("unexpected null on:" + i, message); - } - ack = createAck(consumerInfo, message, numMessages, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.send(ack); - - // Commit - connection.request(createCommitTransaction1Phase(connectionInfo, txid)); - } - - private ActiveMQDestination[] destinationList(ActiveMQDestination dest) { - return dest.isComposite() ? dest.getCompositeDestinations() : new ActiveMQDestination[]{dest}; - } - - private int expectedMessageCount(int i, ActiveMQDestination destination) { - return i * (destination.isComposite() ? destination.getCompositeDestinations().length : 1); - } - - public void testQueuePersistentUncommittedAcksLostOnRestart() throws Exception { - - ActiveMQDestination destination = createDestination(); - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - for (int i = 0; i < 4; i++) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - } - - // Begin the transaction. - XATransactionId txid = createXATransaction(sessionInfo); - connection.send(createBeginTransaction(connectionInfo, txid)); - - Message message = null; - for (ActiveMQDestination dest : destinationList(destination)) { - // Setup the consumer and receive the message. - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, dest); - connection.send(consumerInfo); - - for (int i = 0; i < 4; i++) { - message = receiveMessage(connection); - assertNotNull(message); - } - MessageAck ack = createAck(consumerInfo, message, 4, MessageAck.STANDARD_ACK_TYPE); - ack.setTransactionId(txid); - connection.request(ack); - } - - // Don't commit - - // restart the broker. - restartBroker(); - - // Setup the consumer and receive the message. - connection = createConnection(); - connectionInfo = createConnectionInfo(); - sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - - for (ActiveMQDestination dest : destinationList(destination)) { - // Setup the consumer and receive the message. - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, dest); - connection.send(consumerInfo); - - for (int i = 0; i < 4; i++) { - message = receiveMessage(connection); - assertNotNull(message); - } - } - - assertNoMessagesLeft(connection); - } - - @Override - protected PolicyEntry getDefaultPolicy() { - PolicyEntry policyEntry = super.getDefaultPolicy(); - policyEntry.setPrioritizedMessages(prioritySupport); - return policyEntry; - } - - public static Test suite() { - return suite(XARecoveryBrokerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - protected ActiveMQDestination createDestination() { - return new ActiveMQQueue(getClass().getName() + "." + getName()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryBrokerTest.java deleted file mode 100644 index 5bb676ebf4..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryBrokerTest.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.activemq.broker.advisory; - -import junit.framework.Test; - -import org.apache.activemq.advisory.AdvisorySupport; -import org.apache.activemq.broker.BrokerTestSupport; -import org.apache.activemq.broker.StubConnection; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ConnectionInfo; -import org.apache.activemq.command.ConsumerInfo; -import org.apache.activemq.command.Message; -import org.apache.activemq.command.ProducerInfo; -import org.apache.activemq.command.RemoveInfo; -import org.apache.activemq.command.SessionInfo; - -public class AdvisoryBrokerTest extends BrokerTestSupport { - - public void testConnectionAdvisories() throws Exception { - - ActiveMQDestination destination = AdvisorySupport.getConnectionAdvisoryTopic(); - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(100); - - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(consumerInfo1); - - // We should get an advisory of our own connection. - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - assertEquals(((ConnectionInfo) m1.getDataStructure()).getConnectionId(), connectionInfo1.getConnectionId()); - - // Setup a second connection - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - connection2.send(connectionInfo2); - - // We should get an advisory of the second connection. - m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - assertEquals(((ConnectionInfo) m1.getDataStructure()).getConnectionId(), connectionInfo2.getConnectionId()); - - // Close the second connection. - connection2.send(closeConnectionInfo(connectionInfo2)); - connection2.stop(); - - // We should get an advisory of the second connection closing - m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - RemoveInfo r = (RemoveInfo) m1.getDataStructure(); - assertEquals(r.getObjectId(), connectionInfo2.getConnectionId()); - - assertNoMessagesLeft(connection1); - } - - public void testConsumerAdvisories() throws Exception { - - ActiveMQDestination queue = new ActiveMQQueue("test"); - ActiveMQDestination destination = AdvisorySupport.getConsumerAdvisoryTopic(queue); - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(100); - - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(consumerInfo1); - - // We should not see and advisory for the advisory consumer. - assertNoMessagesLeft(connection1); - - // Setup a second consumer. - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, queue); - consumerInfo1.setPrefetchSize(100); - - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.send(consumerInfo2); - - // We should get an advisory of the new consumer. - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - assertEquals(((ConsumerInfo) m1.getDataStructure()).getConsumerId(), consumerInfo2.getConsumerId()); - - // Close the second connection. - connection2.request(closeConnectionInfo(connectionInfo2)); - connection2.stop(); - - // We should get an advisory of the consumer closing - m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - RemoveInfo r = (RemoveInfo) m1.getDataStructure(); - assertEquals(r.getObjectId(), consumerInfo2.getConsumerId()); - - assertNoMessagesLeft(connection2); - } - - public void testConsumerAdvisoriesReplayed() throws Exception { - - ActiveMQDestination queue = new ActiveMQQueue("test"); - ActiveMQDestination destination = AdvisorySupport.getConsumerAdvisoryTopic(queue); - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - - // Setup a second consumer. - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, queue); - consumerInfo2.setPrefetchSize(100); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.send(consumerInfo2); - - // We should get an advisory of the previous consumer. - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(100); - connection1.send(consumerInfo1); - - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - assertEquals(((ConsumerInfo) m1.getDataStructure()).getConsumerId(), consumerInfo2.getConsumerId()); - - // Close the second connection. - connection2.request(closeConnectionInfo(connectionInfo2)); - connection2.stop(); - - // We should get an advisory of the consumer closing - m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - RemoveInfo r = (RemoveInfo) m1.getDataStructure(); - assertEquals(r.getObjectId(), consumerInfo2.getConsumerId()); - - assertNoMessagesLeft(connection2); - } - - public void testProducerAdvisories() throws Exception { - - ActiveMQDestination queue = new ActiveMQQueue("test"); - ActiveMQDestination destination = AdvisorySupport.getProducerAdvisoryTopic(queue); - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(100); - - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(consumerInfo1); - - assertNoMessagesLeft(connection1); - - // Setup a producer. - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); - producerInfo2.setDestination(queue); - - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.send(producerInfo2); - - // We should get an advisory of the new producer. - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - assertEquals(((ProducerInfo) m1.getDataStructure()).getProducerId(), producerInfo2.getProducerId()); - - // Close the second connection. - connection2.request(closeConnectionInfo(connectionInfo2)); - connection2.stop(); - - // We should get an advisory of the producer closing - m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - RemoveInfo r = (RemoveInfo) m1.getDataStructure(); - assertEquals(r.getObjectId(), producerInfo2.getProducerId()); - - assertNoMessagesLeft(connection2); - } - - public void testProducerAdvisoriesReplayed() throws Exception { - - ActiveMQDestination queue = new ActiveMQQueue("test"); - ActiveMQDestination destination = AdvisorySupport.getProducerAdvisoryTopic(queue); - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - - // Setup a producer. - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); - producerInfo2.setDestination(queue); - - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.send(producerInfo2); - - // Create the advisory consumer.. it should see the previous producer - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(100); - connection1.send(consumerInfo1); - - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - assertEquals(((ProducerInfo) m1.getDataStructure()).getProducerId(), producerInfo2.getProducerId()); - - // Close the second connection. - connection2.request(closeConnectionInfo(connectionInfo2)); - connection2.stop(); - - // We should get an advisory of the producer closing - m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - RemoveInfo r = (RemoveInfo) m1.getDataStructure(); - assertEquals(r.getObjectId(), producerInfo2.getProducerId()); - - assertNoMessagesLeft(connection2); - } - - public void testProducerAdvisoriesReplayedOnlyTargetNewConsumer() throws Exception { - - ActiveMQDestination queue = new ActiveMQQueue("test"); - ActiveMQDestination destination = AdvisorySupport.getProducerAdvisoryTopic(queue); - - // Setup a first connection - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - // Create the first consumer.. - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - consumerInfo1.setPrefetchSize(100); - connection1.send(consumerInfo1); - - // Setup a producer. - StubConnection connection2 = createConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ProducerInfo producerInfo2 = createProducerInfo(sessionInfo2); - producerInfo2.setDestination(queue); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.send(producerInfo2); - - Message m1 = receiveMessage(connection1); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - assertEquals(((ProducerInfo) m1.getDataStructure()).getProducerId(), producerInfo2.getProducerId()); - - // Create the 2nd consumer.. - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - consumerInfo2.setPrefetchSize(100); - connection2.send(consumerInfo2); - - // The second consumer should se a replay - m1 = receiveMessage(connection2); - assertNotNull(m1); - assertNotNull(m1.getDataStructure()); - assertEquals(((ProducerInfo) m1.getDataStructure()).getProducerId(), producerInfo2.getProducerId()); - - // But the first consumer should not see the replay. - assertNoMessagesLeft(connection1); - } - - public static Test suite() { - return suite(AdvisoryBrokerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryDuplexNetworkBridgeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryDuplexNetworkBridgeTest.java deleted file mode 100644 index 5b00d629bd..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryDuplexNetworkBridgeTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.advisory; - -import java.net.URI; - -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; - -public class AdvisoryDuplexNetworkBridgeTest extends AdvisoryNetworkBridgeTest { - - @Override - public void createBroker1() throws Exception { - broker1 = new BrokerService(); - broker1.setBrokerName("broker1"); - broker1.addConnector("tcp://localhost:61617"); - broker1.setUseJmx(false); - broker1.setPersistent(false); - broker1.start(); - broker1.waitUntilStarted(); - } - - @Override - public void createBroker2() throws Exception { - broker2 = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/network/duplexLocalBroker.xml")); - broker2.start(); - broker2.waitUntilStarted(); - } - - @Override - public void assertCreatedByDuplex(boolean createdByDuplex) { - assertTrue(createdByDuplex); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryJmxTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryJmxTest.java deleted file mode 100644 index 003dfb8aff..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryJmxTest.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.activemq.broker.advisory; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.MessageConsumer; -import javax.jms.Session; -import javax.management.MBeanServerConnection; -import javax.management.MBeanServerInvocationHandler; -import javax.management.ObjectName; -import javax.management.remote.JMXConnector; -import javax.management.remote.JMXConnectorFactory; -import javax.management.remote.JMXServiceURL; - -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.jmx.BrokerViewMBean; -import org.apache.activemq.broker.jmx.ManagementContext; -import org.apache.activemq.command.ActiveMQMessage; -import org.apache.activemq.command.DestinationInfo; - -public class AdvisoryJmxTest extends EmbeddedBrokerTestSupport { - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setPersistent(isPersistent()); - answer.addConnector(bindAddress); - ManagementContext context = new ManagementContext(); - context.setConnectorPort(1199); - answer.setManagementContext(context); - return answer; - } - - public void testCreateDeleteDestinations() throws Exception { - JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1199/jmxrmi"); - JMXConnector connector = JMXConnectorFactory.connect(url, null); - connector.connect(); - MBeanServerConnection connection = connector.getMBeanServerConnection(); - ObjectName name = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost"); - BrokerViewMBean brokerMbean = MBeanServerInvocationHandler.newProxyInstance(connection, name, BrokerViewMBean.class, true); - Connection conn = createConnection(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = sess.createConsumer(sess.createTopic("ActiveMQ.Advisory.Queue")); - conn.start(); - Destination dest = sess.createQueue("test"); - - brokerMbean.addQueue("test"); - - ActiveMQMessage msg = (ActiveMQMessage) consumer.receive(1000); - assertNotNull(msg); - assertTrue(msg.getDataStructure() instanceof DestinationInfo); - assertEquals(((DestinationInfo) msg.getDataStructure()).getDestination(), dest); - assertEquals(((DestinationInfo) msg.getDataStructure()).getOperationType(), 0); - - brokerMbean.removeQueue("test"); - - msg = (ActiveMQMessage) consumer.receive(1000); - assertNotNull(msg); - assertTrue(msg.getDataStructure() instanceof DestinationInfo); - assertEquals(((DestinationInfo) msg.getDataStructure()).getDestination(), dest); - assertEquals(((DestinationInfo) msg.getDataStructure()).getOperationType(), 1); - - brokerMbean.addQueue("test"); - msg = (ActiveMQMessage) consumer.receive(1000); - assertNotNull(msg); - assertTrue(msg.getDataStructure() instanceof DestinationInfo); - assertEquals(((DestinationInfo) msg.getDataStructure()).getDestination(), dest); - assertEquals(((DestinationInfo) msg.getDataStructure()).getOperationType(), 0); - assertEquals(((DestinationInfo) msg.getDataStructure()).getOperationType(), 0); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryNetworkBridgeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryNetworkBridgeTest.java deleted file mode 100644 index f2b368c993..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/advisory/AdvisoryNetworkBridgeTest.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.activemq.broker.advisory; - -import javax.jms.Connection; -import javax.jms.MessageConsumer; -import javax.jms.Session; -import java.net.URI; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.advisory.AdvisorySupport; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQMessage; -import org.apache.activemq.command.BrokerInfo; - -public class AdvisoryNetworkBridgeTest extends TestCase { - - BrokerService broker1; - BrokerService broker2; - - public void testAdvisory() throws Exception { - createBroker1(); - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://broker1"); - Connection conn = factory.createConnection(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - MessageConsumer consumer = sess.createConsumer(AdvisorySupport.getNetworkBridgeAdvisoryTopic()); - - Thread.sleep(1000); - - createBroker2(); - - ActiveMQMessage advisory = (ActiveMQMessage) consumer.receive(2000); - assertNotNull(advisory); - assertTrue(advisory.getDataStructure() instanceof BrokerInfo); - assertTrue(advisory.getBooleanProperty("started")); - assertCreatedByDuplex(advisory.getBooleanProperty("createdByDuplex")); - - broker2.stop(); - broker2.waitUntilStopped(); - - advisory = (ActiveMQMessage) consumer.receive(2000); - assertNotNull(advisory); - assertTrue(advisory.getDataStructure() instanceof BrokerInfo); - assertFalse(advisory.getBooleanProperty("started")); - - conn.close(); - } - - public void testAddConsumerLater() throws Exception { - createBroker1(); - - createBroker2(); - - Thread.sleep(1000); - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://broker1"); - Connection conn = factory.createConnection(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - MessageConsumer consumer = sess.createConsumer(AdvisorySupport.getNetworkBridgeAdvisoryTopic()); - - ActiveMQMessage advisory = (ActiveMQMessage) consumer.receive(2000); - assertNotNull(advisory); - assertTrue(advisory.getDataStructure() instanceof BrokerInfo); - assertTrue(advisory.getBooleanProperty("started")); - assertCreatedByDuplex(advisory.getBooleanProperty("createdByDuplex")); - - broker2.stop(); - broker2.waitUntilStopped(); - - advisory = (ActiveMQMessage) consumer.receive(2000); - assertNotNull(advisory); - assertTrue(advisory.getDataStructure() instanceof BrokerInfo); - assertFalse(advisory.getBooleanProperty("started")); - - consumer = sess.createConsumer(AdvisorySupport.getNetworkBridgeAdvisoryTopic()); - advisory = (ActiveMQMessage) consumer.receive(1000); - assertNull(advisory); - - conn.close(); - - } - - public void assertCreatedByDuplex(boolean createdByDuplex) { - assertFalse(createdByDuplex); - } - - public void createBroker1() throws Exception { - broker1 = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/network/reconnect-broker1.xml")); - broker1.start(); - broker1.waitUntilStarted(); - } - - public void createBroker2() throws Exception { - broker2 = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/network/reconnect-broker2.xml")); - broker2.start(); - broker2.waitUntilStarted(); - } - - @Override - protected void tearDown() throws Exception { - broker1.stop(); - broker1.waitUntilStopped(); - - broker2.stop(); - broker2.waitUntilStopped(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/destinations-on-start.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/destinations-on-start.xml deleted file mode 100644 index f0ee482b56..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/destinations-on-start.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/exclusive-consumer-startup-destination.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/exclusive-consumer-startup-destination.xml deleted file mode 100644 index 5c10b7db78..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/exclusive-consumer-startup-destination.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveLeaseQuiesceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveLeaseQuiesceTest.java deleted file mode 100644 index bfcec02e46..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveLeaseQuiesceTest.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.activemq.broker.ft; - -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.util.LeaseLockerIOExceptionHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DbRestartJDBCQueueMasterSlaveLeaseQuiesceTest extends DbRestartJDBCQueueMasterSlaveLeaseTest { - - private static final transient Logger LOG = LoggerFactory.getLogger(DbRestartJDBCQueueMasterSlaveLeaseQuiesceTest.class); - - private long restartDelay = 2000; - - @Override - protected void configureBroker(BrokerService brokerService) { - // master and slave survive db restart and retain master/slave status - LeaseLockerIOExceptionHandler stopConnectors = new LeaseLockerIOExceptionHandler(); - brokerService.setIoExceptionHandler(stopConnectors); - } - - @Override - protected void delayTillRestartRequired() { - if (restartDelay > 2000) { - LOG.info("delay for more than lease quantum. While Db is offline, master should stay alive but could loose lease"); - } else { - LOG.info("delay for less than lease quantum. While Db is offline, master should stay alive"); - } - try { - TimeUnit.MILLISECONDS.sleep(restartDelay); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - @Override - protected void verifyExpectedBroker(int inflightMessageCount) { - if (inflightMessageCount == 0 || (inflightMessageCount == failureCount + 10 && restartDelay <= 500)) { - assertEquals("connected to master", master.getBrokerName(), ((ActiveMQConnection) sendConnection).getBrokerName()); - } else { - // lease expired while DB was offline, either or master/slave can grab it so assert is not deterministic - // but we still need to validate sent == received - } - } - - @Override - public void setUp() throws Exception { - restartDelay = 2000; - super.setUp(); - } - - public void testSendReceiveWithLeaseExpiry() throws Exception { - restartDelay = 10000; - testSendReceive(); - } - - // ignore this test case - @Override - public void testAdvisory() throws Exception { - } - - @Override - public void testSendReceive() throws Exception { - // Ignore this test for now, see AMQ-4975 - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveLeaseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveLeaseTest.java deleted file mode 100644 index 807b3e2149..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveLeaseTest.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.activemq.broker.ft; - -import java.io.IOException; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; -import org.apache.activemq.store.jdbc.LeaseDatabaseLocker; -import org.apache.activemq.util.LeaseLockerIOExceptionHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DbRestartJDBCQueueMasterSlaveLeaseTest extends DbRestartJDBCQueueMasterSlaveTest { - - private static final transient Logger LOG = LoggerFactory.getLogger(DbRestartJDBCQueueMasterSlaveLeaseTest.class); - - @Override - protected void configureJdbcPersistenceAdapter(JDBCPersistenceAdapter persistenceAdapter) throws IOException { - super.configureJdbcPersistenceAdapter(persistenceAdapter); - persistenceAdapter.setLocker(new LeaseDatabaseLocker()); - persistenceAdapter.getLocker().setLockAcquireSleepInterval(getLockAcquireSleepInterval()); - persistenceAdapter.setLockKeepAlivePeriod(getLockKeepAlivePeriod()); - } - - @Override - protected void configureBroker(BrokerService brokerService) { - //let the brokers die on exception and master should have lease on restart - // which will delay slave start till it expires - LeaseLockerIOExceptionHandler ioExceptionHandler = new LeaseLockerIOExceptionHandler(); - ioExceptionHandler.setIgnoreSQLExceptions(false); - ioExceptionHandler.setStopStartConnectors(false); - ioExceptionHandler.setResumeCheckSleepPeriod(500L); - brokerService.setIoExceptionHandler(ioExceptionHandler); - } - - private long getLockKeepAlivePeriod() { - return 1000; - } - - private long getLockAcquireSleepInterval() { - return 8000; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveTest.java deleted file mode 100644 index d743d46001..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueMasterSlaveTest.java +++ /dev/null @@ -1,155 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.ft; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TransactionRolledBackException; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQMessage; -import org.apache.activemq.command.MessageId; -import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; -import org.apache.derby.jdbc.EmbeddedDataSource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DbRestartJDBCQueueMasterSlaveTest extends JDBCQueueMasterSlaveTest { - - private static final transient Logger LOG = LoggerFactory.getLogger(DbRestartJDBCQueueMasterSlaveTest.class); - - @Override - protected void messageSent() throws Exception { - verifyExpectedBroker(inflightMessageCount); - if (++inflightMessageCount == failureCount) { - LOG.info("STOPPING DB!@!!!!"); - final EmbeddedDataSource ds = ((SyncCreateDataSource) getExistingDataSource()).getDelegate(); - ds.setShutdownDatabase("shutdown"); - LOG.info("DB STOPPED!@!!!!"); - - Thread dbRestartThread = new Thread("db-re-start-thread") { - @Override - public void run() { - delayTillRestartRequired(); - ds.setShutdownDatabase("false"); - LOG.info("DB RESTARTED!@!!!!"); - } - }; - dbRestartThread.start(); - } - verifyExpectedBroker(inflightMessageCount); - } - - protected void verifyExpectedBroker(int inflightMessageCount) { - if (inflightMessageCount == 0) { - assertEquals("connected to master", master.getBrokerName(), ((ActiveMQConnection) sendConnection).getBrokerName()); - } else if (inflightMessageCount == failureCount + 10) { - assertEquals("connected to slave, count:" + inflightMessageCount, slave.get().getBrokerName(), ((ActiveMQConnection) sendConnection).getBrokerName()); - } - } - - protected void delayTillRestartRequired() { - LOG.info("Waiting for master broker to Stop"); - master.waitUntilStopped(); - } - - @Override - protected void sendToProducer(MessageProducer producer, - Destination producerDestination, - Message message) throws JMSException { - producer.send(producerDestination, message); - } - - @Override - protected Session createReceiveSession(Connection receiveConnection) throws Exception { - return receiveConnection.createSession(true, Session.SESSION_TRANSACTED); - } - - @Override - protected void consumeMessage(Message message, List messageList) { - try { - receiveSession.commit(); - super.consumeMessage(message, messageList); - } catch (JMSException e) { - LOG.info("Failed to commit message receipt: " + message, e); - try { - receiveSession.rollback(); - } catch (JMSException ignored) { - } - - if (e instanceof TransactionRolledBackException) { - TransactionRolledBackException transactionRolledBackException = (TransactionRolledBackException) e; - if (transactionRolledBackException.getMessage().indexOf("in doubt") != -1) { - // failover chucked bc there is a missing reply to a commit. - // failover is involved b/c the store exception is handled broker side and the client just - // sees a disconnect (socket.close()). - // If the client needs to be aware of the failure then it should not use IOExceptionHandler - // so that the exception will propagate back - - // for this test case: - // the commit may have got there and the reply is lost "or" the commit may be lost. - // so we may or may not get a resend. - // - // At the application level we need to determine if the message is there or not which is not trivial - // for this test we assert received == sent - // so we need to know whether the message will be replayed. - // we can ask the store b/c we know it is jdbc - guess we could go through a destination - // message store interface also or use jmx - java.sql.Connection dbConnection = null; - try { - ActiveMQMessage mqMessage = (ActiveMQMessage) message; - MessageId id = mqMessage.getMessageId(); - dbConnection = sharedDs.getConnection(); - PreparedStatement s = dbConnection.prepareStatement(((JDBCPersistenceAdapter) connectedToBroker().getPersistenceAdapter()).getStatements().getFindMessageStatement()); - s.setString(1, id.getProducerId().toString()); - s.setLong(2, id.getProducerSequenceId()); - ResultSet rs = s.executeQuery(); - - if (!rs.next()) { - // message is gone, so lets count it as consumed - LOG.info("On TransactionRolledBackException we know that the ack/commit got there b/c message is gone so we count it: " + mqMessage); - super.consumeMessage(message, messageList); - } else { - LOG.info("On TransactionRolledBackException we know that the ack/commit was lost so we expect a replay of: " + mqMessage); - } - } catch (Exception dbe) { - dbe.printStackTrace(); - } finally { - try { - dbConnection.close(); - } catch (SQLException e1) { - e1.printStackTrace(); - } - } - } - } - } - } - - private BrokerService connectedToBroker() { - return ((ActiveMQConnection) receiveConnection).getBrokerInfo().getBrokerName().equals("master") ? master : slave.get(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueTest.java deleted file mode 100644 index 2d21fa198a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/DbRestartJDBCQueueTest.java +++ /dev/null @@ -1,165 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.ft; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.ExceptionListener; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.JmsTopicSendReceiveWithTwoConnectionsTest; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.store.jdbc.DataSourceServiceSupport; -import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; -import org.apache.activemq.util.DefaultIOExceptionHandler; -import org.apache.activemq.util.IOHelper; -import org.apache.derby.jdbc.EmbeddedDataSource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DbRestartJDBCQueueTest extends JmsTopicSendReceiveWithTwoConnectionsTest implements ExceptionListener { - - private static final transient Logger LOG = LoggerFactory.getLogger(DbRestartJDBCQueueTest.class); - - public boolean transactedSends = false; - public int failureCount = 25; // or 20 for even tx batch boundary - - int inflightMessageCount = 0; - EmbeddedDataSource sharedDs; - BrokerService broker; - final CountDownLatch restartDBLatch = new CountDownLatch(1); - - @Override - protected void setUp() throws Exception { - setAutoFail(true); - topic = false; - verbose = true; - // startup db - sharedDs = (EmbeddedDataSource) DataSourceServiceSupport.createDataSource(IOHelper.getDefaultDataDirectory()); - - broker = new BrokerService(); - - DefaultIOExceptionHandler handler = new DefaultIOExceptionHandler(); - handler.setIgnoreSQLExceptions(false); - handler.setStopStartConnectors(true); - broker.setIoExceptionHandler(handler); - broker.addConnector("tcp://localhost:0"); - broker.setUseJmx(false); - broker.setPersistent(true); - broker.setDeleteAllMessagesOnStartup(true); - JDBCPersistenceAdapter persistenceAdapter = new JDBCPersistenceAdapter(); - persistenceAdapter.setDataSource(sharedDs); - persistenceAdapter.setUseLock(false); - persistenceAdapter.setLockKeepAlivePeriod(500); - persistenceAdapter.getLocker().setLockAcquireSleepInterval(500); - broker.setPersistenceAdapter(persistenceAdapter); - broker.start(); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - broker.stop(); - } - - @Override - protected Session createSendSession(Connection sendConnection) throws Exception { - if (transactedSends) { - return sendConnection.createSession(true, Session.SESSION_TRANSACTED); - } else { - return sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory f = new ActiveMQConnectionFactory("failover://" + broker.getTransportConnectors().get(0).getPublishableConnectString()); - f.setExceptionListener(this); - return f; - } - - @Override - protected void messageSent() throws Exception { - if (++inflightMessageCount == failureCount) { - LOG.info("STOPPING DB!@!!!!"); - final EmbeddedDataSource ds = sharedDs; - ds.setShutdownDatabase("shutdown"); - try { - ds.getConnection(); - } catch (Exception ignored) { - } - LOG.info("DB STOPPED!@!!!!"); - - Thread dbRestartThread = new Thread("db-re-start-thread") { - @Override - public void run() { - LOG.info("Sleeping for 10 seconds before allowing db restart"); - try { - restartDBLatch.await(10, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - ds.setShutdownDatabase("false"); - LOG.info("DB RESTARTED!@!!!!"); - } - }; - dbRestartThread.start(); - } - } - - @Override - protected void sendToProducer(MessageProducer producer, - Destination producerDestination, - Message message) throws JMSException { - { - // do some retries as db failures filter back to the client until broker sees - // db lock failure and shuts down - boolean sent = false; - do { - try { - producer.send(producerDestination, message); - - if (transactedSends && ((inflightMessageCount + 1) % 10 == 0 || (inflightMessageCount + 1) >= messageCount)) { - LOG.info("committing on send: " + inflightMessageCount + " message: " + message); - session.commit(); - } - - sent = true; - } catch (JMSException e) { - LOG.info("Exception on producer send:", e); - try { - Thread.sleep(2000); - } catch (InterruptedException ignored) { - } - } - } while (!sent); - - } - } - - @Override - public void onException(JMSException exception) { - LOG.error("exception on connection: ", exception); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/JDBCQueueMasterSlaveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/JDBCQueueMasterSlaveTest.java deleted file mode 100644 index 9faf3af2a3..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/JDBCQueueMasterSlaveTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.ft; - -import javax.sql.DataSource; -import java.io.IOException; -import java.net.URI; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.store.jdbc.DataSourceServiceSupport; -import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; -import org.apache.activemq.util.DefaultIOExceptionHandler; -import org.apache.activemq.util.IOHelper; -import org.apache.derby.jdbc.EmbeddedDataSource; - -public class JDBCQueueMasterSlaveTest extends QueueMasterSlaveTestSupport { - - protected DataSource sharedDs; - protected String MASTER_URL = "tcp://localhost:62001"; - protected String SLAVE_URL = "tcp://localhost:62002"; - - @Override - protected void setUp() throws Exception { - // startup db - sharedDs = new SyncCreateDataSource((EmbeddedDataSource) DataSourceServiceSupport.createDataSource(IOHelper.getDefaultDataDirectory())); - super.setUp(); - } - - @Override - protected void createMaster() throws Exception { - master = new BrokerService(); - master.setBrokerName("master"); - master.addConnector(MASTER_URL); - master.setUseJmx(false); - master.setPersistent(true); - master.setDeleteAllMessagesOnStartup(true); - JDBCPersistenceAdapter persistenceAdapter = new JDBCPersistenceAdapter(); - persistenceAdapter.setDataSource(getExistingDataSource()); - configureJdbcPersistenceAdapter(persistenceAdapter); - master.setPersistenceAdapter(persistenceAdapter); - configureBroker(master); - master.start(); - } - - protected void configureBroker(BrokerService brokerService) { - DefaultIOExceptionHandler stopBrokerOnStoreException = new DefaultIOExceptionHandler(); - // we want any store io exception to stop the broker - stopBrokerOnStoreException.setIgnoreSQLExceptions(false); - brokerService.setIoExceptionHandler(stopBrokerOnStoreException); - } - - @Override - protected void createSlave() throws Exception { - // use a separate thread as the slave will block waiting for - // the exclusive db lock - Thread t = new Thread() { - @Override - public void run() { - try { - BrokerService broker = new BrokerService(); - broker.setBrokerName("slave"); - TransportConnector connector = new TransportConnector(); - connector.setUri(new URI(SLAVE_URL)); - broker.addConnector(connector); - // no need for broker.setMasterConnectorURI(masterConnectorURI) - // as the db lock provides the slave/master initialisation - broker.setUseJmx(false); - broker.setPersistent(true); - JDBCPersistenceAdapter persistenceAdapter = new JDBCPersistenceAdapter(); - persistenceAdapter.setDataSource(getExistingDataSource()); - persistenceAdapter.setCreateTablesOnStartup(false); - broker.setPersistenceAdapter(persistenceAdapter); - configureJdbcPersistenceAdapter(persistenceAdapter); - configureBroker(broker); - broker.start(); - slave.set(broker); - slaveStarted.countDown(); - } catch (IllegalStateException expectedOnShutdown) { - } catch (Exception e) { - fail("failed to start slave broker, reason:" + e); - } - } - }; - t.start(); - } - - protected void configureJdbcPersistenceAdapter(JDBCPersistenceAdapter persistenceAdapter) throws IOException { - persistenceAdapter.setLockKeepAlivePeriod(500); - persistenceAdapter.getLocker().setLockAcquireSleepInterval(500); - } - - protected DataSource getExistingDataSource() throws Exception { - return sharedDs; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveSingleUrlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveSingleUrlTest.java deleted file mode 100644 index c318687647..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveSingleUrlTest.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.activemq.broker.ft; - -import java.io.File; -import java.net.URI; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.leveldb.LevelDBStore; -import org.junit.Ignore; - -public class QueueMasterSlaveSingleUrlTest extends QueueMasterSlaveTestSupport { - - private final String brokerUrl = "tcp://localhost:62001"; - private final String singleUriString = "failover://(" + brokerUrl + ")?randomize=false"; - - @Override - protected void setUp() throws Exception { - setAutoFail(true); - super.setUp(); - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(singleUriString); - } - - @Override - protected void createMaster() throws Exception { - master = new BrokerService(); - master.setBrokerName("shared-master"); - configureSharedPersistenceAdapter(master); - master.addConnector(brokerUrl); - master.start(); - } - - private void configureSharedPersistenceAdapter(BrokerService broker) throws Exception { - LevelDBStore adapter = new LevelDBStore(); - adapter.setDirectory(new File("shared")); - broker.setPersistenceAdapter(adapter); - } - - @Override - protected void createSlave() throws Exception { - new Thread(new Runnable() { - @Override - public void run() { - try { - BrokerService broker = new BrokerService(); - broker.setBrokerName("shared-slave"); - configureSharedPersistenceAdapter(broker); - // add transport as a service so that it is bound on start, after store started - final TransportConnector tConnector = new TransportConnector(); - tConnector.setUri(new URI(brokerUrl)); - broker.addConnector(tConnector); - - broker.start(); - slave.set(broker); - slaveStarted.countDown(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - }).start(); - } - - // The @Ignore is just here for documentation, since this is a JUnit3 test - // I added the sleep because without it the two other test cases fail. I haven't looked into it, but - // my guess whatever setUp does isn't really finished when the teardown runs. - @Ignore("See https://issues.apache.org/jira/browse/AMQ-5164") - @Override - public void testAdvisory() throws Exception { - Thread.sleep(5 * 1000); - //super.testAdvisory(); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveTestSupport.java deleted file mode 100644 index 9f8ab5c327..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveTestSupport.java +++ /dev/null @@ -1,156 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.ft; - -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.TextMessage; -import java.io.File; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.JmsTopicSendReceiveWithTwoConnectionsTest; -import org.apache.activemq.advisory.AdvisorySupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.xbean.BrokerFactoryBean; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.ClassPathResource; - -/** - * Test failover for Queues - */ -abstract public class QueueMasterSlaveTestSupport extends JmsTopicSendReceiveWithTwoConnectionsTest { - - private static final transient Logger LOG = LoggerFactory.getLogger(QueueMasterSlaveTestSupport.class); - - protected BrokerService master; - protected AtomicReference slave = new AtomicReference<>(); - protected CountDownLatch slaveStarted = new CountDownLatch(1); - protected int inflightMessageCount; - protected int failureCount = 50; - protected String uriString = "failover://(tcp://localhost:62001,tcp://localhost:62002)?randomize=false&useExponentialBackOff=false"; - - @Override - protected void setUp() throws Exception { - setMaxTestTime(TimeUnit.MINUTES.toMillis(10)); - setAutoFail(true); - if (System.getProperty("basedir") == null) { - File file = new File("."); - System.setProperty("basedir", file.getAbsolutePath()); - } - super.messageCount = 500; - failureCount = super.messageCount / 2; - super.topic = isTopic(); - createMaster(); - createSlave(); - // wait for thing to connect - Thread.sleep(1000); - super.setUp(); - } - - protected String getSlaveXml() { - return "org/apache/activemq/broker/ft/slave.xml"; - } - - protected String getMasterXml() { - return "org/apache/activemq/broker/ft/master.xml"; - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - master.stop(); - master.waitUntilStopped(); - slaveStarted.await(60, TimeUnit.SECONDS); - BrokerService brokerService = slave.get(); - if (brokerService != null) { - brokerService.stop(); - } - master.stop(); - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(uriString); - } - - @Override - protected void messageSent() throws Exception { - if (++inflightMessageCount == failureCount) { - Thread.sleep(1000); - LOG.error("MASTER STOPPED!@!!!!"); - master.stop(); - } - } - - protected boolean isTopic() { - return false; - } - - protected void createMaster() throws Exception { - BrokerFactoryBean brokerFactory = new BrokerFactoryBean(new ClassPathResource(getMasterXml())); - brokerFactory.afterPropertiesSet(); - master = brokerFactory.getBroker(); - master.start(); - } - - protected void createSlave() throws Exception { - BrokerFactoryBean brokerFactory = new BrokerFactoryBean(new ClassPathResource(getSlaveXml())); - brokerFactory.afterPropertiesSet(); - BrokerService broker = brokerFactory.getBroker(); - broker.start(); - slave.set(broker); - slaveStarted.countDown(); - } - - public void testVirtualTopicFailover() throws Exception { - - MessageConsumer qConsumer = session.createConsumer(new ActiveMQQueue("Consumer.A.VirtualTopic.TA1")); - assertNull("No message there yet", qConsumer.receive(1000)); - qConsumer.close(); - assertTrue(!master.isSlave()); - master.stop(); - assertTrue("slave started", slaveStarted.await(60, TimeUnit.SECONDS)); - assertTrue(!slave.get().isSlave()); - - final String text = "ForUWhenSlaveKicksIn"; - producer.send(new ActiveMQTopic("VirtualTopic.TA1"), session.createTextMessage(text)); - - qConsumer = session.createConsumer(new ActiveMQQueue("Consumer.A.VirtualTopic.TA1")); - - javax.jms.Message message = qConsumer.receive(4000); - assertNotNull("Get message after failover", message); - assertEquals("correct message", text, ((TextMessage) message).getText()); - } - - public void testAdvisory() throws Exception { - MessageConsumer advConsumer = session.createConsumer(AdvisorySupport.getMasterBrokerAdvisoryTopic()); - - master.stop(); - assertTrue("slave started", slaveStarted.await(60, TimeUnit.SECONDS)); - LOG.info("slave started"); - Message advisoryMessage = advConsumer.receive(5000); - LOG.info("received " + advisoryMessage); - assertNotNull("Didn't received advisory", advisoryMessage); - - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveTestUsingSharedFileTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveTestUsingSharedFileTest.java deleted file mode 100644 index 5d204aa022..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/QueueMasterSlaveTestUsingSharedFileTest.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.activemq.broker.ft; - -public class QueueMasterSlaveTestUsingSharedFileTest extends QueueMasterSlaveTestSupport { - - @Override - protected String getSlaveXml() { - return "org/apache/activemq/broker/ft/sharedFileSlave.xml"; - } - - @Override - protected String getMasterXml() { - return "org/apache/activemq/broker/ft/sharedFileMaster.xml"; - } - - @Override - protected void createSlave() throws Exception { - // Start the Brokers async since starting them up could be a blocking operation.. - new Thread(new Runnable() { - @Override - public void run() { - try { - QueueMasterSlaveTestUsingSharedFileTest.super.createSlave(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - }).start(); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/SyncCreateDataSource.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/SyncCreateDataSource.java deleted file mode 100644 index c795f8e058..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/SyncCreateDataSource.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.activemq.broker.ft; - -import javax.sql.DataSource; -import java.io.PrintWriter; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.SQLFeatureNotSupportedException; -import java.util.logging.Logger; - -import org.apache.derby.jdbc.EmbeddedDataSource; - -// prevent concurrent calls from attempting to create the db at the same time -// can result in "already exists in this jvm" errors - -public class SyncCreateDataSource implements DataSource { - - final EmbeddedDataSource delegate; - - SyncCreateDataSource(EmbeddedDataSource dataSource) { - this.delegate = dataSource; - } - - @Override - public Connection getConnection() throws SQLException { - synchronized (this) { - return delegate.getConnection(); - } - } - - @Override - public Connection getConnection(String username, String password) throws SQLException { - synchronized (this) { - return delegate.getConnection(); - } - } - - @Override - public PrintWriter getLogWriter() throws SQLException { - return null; - } - - @Override - public void setLogWriter(PrintWriter out) throws SQLException { - } - - @Override - public int getLoginTimeout() throws SQLException { - return 0; - } - - @Override - public void setLoginTimeout(int seconds) throws SQLException { - } - - @Override - public T unwrap(Class iface) throws SQLException { - return null; - } - - @Override - public boolean isWrapperFor(Class iface) throws SQLException { - return false; - } - - EmbeddedDataSource getDelegate() { - return delegate; - } - - @Override - public Logger getParentLogger() throws SQLFeatureNotSupportedException { - return null; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/kahaDbJdbcLeaseQueueMasterSlaveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/kahaDbJdbcLeaseQueueMasterSlaveTest.java deleted file mode 100644 index 9a684b6bc4..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/kahaDbJdbcLeaseQueueMasterSlaveTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.ft; - -import javax.sql.DataSource; -import java.io.IOException; -import java.net.URI; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.store.jdbc.DataSourceServiceSupport; -import org.apache.activemq.store.jdbc.LeaseDatabaseLocker; -import org.apache.activemq.store.jdbc.Statements; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.util.DefaultIOExceptionHandler; -import org.apache.activemq.util.IOHelper; -import org.apache.derby.jdbc.EmbeddedDataSource; - -public class kahaDbJdbcLeaseQueueMasterSlaveTest extends QueueMasterSlaveTestSupport { - - protected DataSource sharedDs; - protected String MASTER_URL = "tcp://localhost:62001"; - protected String SLAVE_URL = "tcp://localhost:62002"; - - @Override - protected void setUp() throws Exception { - // startup db - sharedDs = new SyncCreateDataSource((EmbeddedDataSource) DataSourceServiceSupport.createDataSource(IOHelper.getDefaultDataDirectory())); - super.setUp(); - } - - @Override - protected void createMaster() throws Exception { - master = new BrokerService(); - master.setBrokerName("master"); - master.addConnector(MASTER_URL); - master.setUseJmx(false); - master.setPersistent(true); - master.setDeleteAllMessagesOnStartup(true); - KahaDBPersistenceAdapter kahaDBPersistenceAdapter = (KahaDBPersistenceAdapter) master.getPersistenceAdapter(); - LeaseDatabaseLocker leaseDatabaseLocker = new LeaseDatabaseLocker(); - leaseDatabaseLocker.setCreateTablesOnStartup(true); - leaseDatabaseLocker.setDataSource(getExistingDataSource()); - leaseDatabaseLocker.setStatements(new Statements()); - kahaDBPersistenceAdapter.setLocker(leaseDatabaseLocker); - configureLocker(kahaDBPersistenceAdapter); - configureBroker(master); - master.start(); - } - - protected void configureBroker(BrokerService brokerService) { - DefaultIOExceptionHandler stopBrokerOnStoreException = new DefaultIOExceptionHandler(); - // we want any store io exception to stop the broker - stopBrokerOnStoreException.setIgnoreSQLExceptions(false); - brokerService.setIoExceptionHandler(stopBrokerOnStoreException); - } - - @Override - protected void createSlave() throws Exception { - // use a separate thread as the slave will block waiting for - // the exclusive db lock - Thread t = new Thread() { - @Override - public void run() { - try { - BrokerService broker = new BrokerService(); - broker.setBrokerName("slave"); - TransportConnector connector = new TransportConnector(); - connector.setUri(new URI(SLAVE_URL)); - broker.addConnector(connector); - broker.setUseJmx(false); - broker.setPersistent(true); - KahaDBPersistenceAdapter kahaDBPersistenceAdapter = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - LeaseDatabaseLocker leaseDatabaseLocker = new LeaseDatabaseLocker(); - leaseDatabaseLocker.setDataSource(getExistingDataSource()); - leaseDatabaseLocker.setStatements(new Statements()); - kahaDBPersistenceAdapter.setLocker(leaseDatabaseLocker); - configureLocker(kahaDBPersistenceAdapter); - configureBroker(broker); - broker.start(); - slave.set(broker); - slaveStarted.countDown(); - } catch (IllegalStateException expectedOnShutdown) { - } catch (Exception e) { - fail("failed to start slave broker, reason:" + e); - } - } - }; - t.start(); - } - - protected void configureLocker(KahaDBPersistenceAdapter kahaDBPersistenceAdapter) throws IOException { - kahaDBPersistenceAdapter.setLockKeepAlivePeriod(500); - kahaDBPersistenceAdapter.getLocker().setLockAcquireSleepInterval(500); - } - - @Override - public void testVirtualTopicFailover() throws Exception { - // Ignoring for now, see AMQ-4842 - } - - protected DataSource getExistingDataSource() throws Exception { - return sharedDs; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/mKahaDbQueueMasterSlaveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/mKahaDbQueueMasterSlaveTest.java deleted file mode 100644 index 222e8e3b88..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/mKahaDbQueueMasterSlaveTest.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.activemq.broker.ft; - -import java.net.URI; -import java.util.LinkedList; -import java.util.List; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.store.kahadb.FilteredKahaDBPersistenceAdapter; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.store.kahadb.MultiKahaDBPersistenceAdapter; - -public class mKahaDbQueueMasterSlaveTest extends QueueMasterSlaveTestSupport { - - protected String MASTER_URL = "tcp://localhost:62001"; - protected String SLAVE_URL = "tcp://localhost:62002"; - - @Override - protected void createMaster() throws Exception { - master = new BrokerService(); - master.setBrokerName("master"); - master.addConnector(MASTER_URL); - master.setUseJmx(false); - master.setPersistent(true); - master.setDeleteAllMessagesOnStartup(true); - - MultiKahaDBPersistenceAdapter mKahaDB = new MultiKahaDBPersistenceAdapter(); - List adapters = new LinkedList<>(); - FilteredKahaDBPersistenceAdapter defaultEntry = new FilteredKahaDBPersistenceAdapter(); - defaultEntry.setPersistenceAdapter(new KahaDBPersistenceAdapter()); - defaultEntry.setPerDestination(true); - adapters.add(defaultEntry); - - mKahaDB.setFilteredPersistenceAdapters(adapters); - master.setPersistenceAdapter(mKahaDB); - - master.start(); - } - - @Override - protected void createSlave() throws Exception { - // use a separate thread as the slave will block waiting for - // the exclusive db lock - Thread t = new Thread() { - @Override - public void run() { - try { - BrokerService broker = new BrokerService(); - broker.setBrokerName("slave"); - TransportConnector connector = new TransportConnector(); - connector.setUri(new URI(SLAVE_URL)); - broker.addConnector(connector); - // no need for broker.setMasterConnectorURI(masterConnectorURI) - // as the db lock provides the slave/master initialisation - broker.setUseJmx(false); - broker.setPersistent(true); - - MultiKahaDBPersistenceAdapter mKahaDB = new MultiKahaDBPersistenceAdapter(); - List adapters = new LinkedList<>(); - FilteredKahaDBPersistenceAdapter defaultEntry = new FilteredKahaDBPersistenceAdapter(); - defaultEntry.setPersistenceAdapter(new KahaDBPersistenceAdapter()); - defaultEntry.setPerDestination(true); - adapters.add(defaultEntry); - - mKahaDB.setFilteredPersistenceAdapters(adapters); - broker.setPersistenceAdapter(mKahaDB); - broker.start(); - slave.set(broker); - slaveStarted.countDown(); - } catch (IllegalStateException expectedOnShutdown) { - } catch (Exception e) { - fail("failed to start slave broker, reason:" + e); - } - } - }; - t.start(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/sharedFileMaster.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/sharedFileMaster.xml deleted file mode 100644 index f5eef67da2..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/sharedFileMaster.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/sharedFileSlave.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/sharedFileSlave.xml deleted file mode 100644 index 7c88a8c689..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/ft/sharedFileSlave.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/mKahaDBXARecoveryBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/mKahaDBXARecoveryBrokerTest.java deleted file mode 100644 index 87f7b74354..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/mKahaDBXARecoveryBrokerTest.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.activemq.broker; - -import java.util.LinkedList; -import java.util.List; - -import junit.framework.Test; - -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.store.kahadb.FilteredKahaDBPersistenceAdapter; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.store.kahadb.MultiKahaDBPersistenceAdapter; - -public class mKahaDBXARecoveryBrokerTest extends XARecoveryBrokerTest { - - @Override - protected void configureBroker(BrokerService broker) throws Exception { - super.configureBroker(broker); - - MultiKahaDBPersistenceAdapter mKahaDB = new MultiKahaDBPersistenceAdapter(); - List adapters = new LinkedList<>(); - FilteredKahaDBPersistenceAdapter defaultEntry = new FilteredKahaDBPersistenceAdapter(); - defaultEntry.setPersistenceAdapter(new KahaDBPersistenceAdapter()); - adapters.add(defaultEntry); - - FilteredKahaDBPersistenceAdapter special = new FilteredKahaDBPersistenceAdapter(); - special.setDestination(new ActiveMQQueue("special")); - special.setPersistenceAdapter(new KahaDBPersistenceAdapter()); - adapters.add(special); - - mKahaDB.setFilteredPersistenceAdapters(adapters); - broker.setPersistenceAdapter(mKahaDB); - } - - public static Test suite() { - return suite(mKahaDBXARecoveryBrokerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - @Override - protected ActiveMQDestination createDestination() { - return new ActiveMQQueue("test,special"); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/mLevelDBXARecoveryBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/mLevelDBXARecoveryBrokerTest.java deleted file mode 100644 index e34baa0983..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/mLevelDBXARecoveryBrokerTest.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.activemq.broker; - -import java.util.LinkedList; -import java.util.List; - -import junit.framework.Test; - -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.store.kahadb.FilteredKahaDBPersistenceAdapter; -import org.apache.activemq.store.kahadb.MultiKahaDBPersistenceAdapter; -import org.apache.activemq.store.leveldb.LevelDBPersistenceAdapter; - -public class mLevelDBXARecoveryBrokerTest extends XARecoveryBrokerTest { - - @Override - protected void configureBroker(BrokerService broker) throws Exception { - super.configureBroker(broker); - - MultiKahaDBPersistenceAdapter mKahaDB = new MultiKahaDBPersistenceAdapter(); - List adapters = new LinkedList<>(); - FilteredKahaDBPersistenceAdapter defaultEntry = new FilteredKahaDBPersistenceAdapter(); - defaultEntry.setPersistenceAdapter(new LevelDBPersistenceAdapter()); - adapters.add(defaultEntry); - - FilteredKahaDBPersistenceAdapter special = new FilteredKahaDBPersistenceAdapter(); - special.setDestination(new ActiveMQQueue("special")); - special.setPersistenceAdapter(new LevelDBPersistenceAdapter()); - adapters.add(special); - - mKahaDB.setFilteredPersistenceAdapters(adapters); - broker.setPersistenceAdapter(mKahaDB); - } - - public static Test suite() { - return suite(mLevelDBXARecoveryBrokerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - @Override - protected ActiveMQDestination createDestination() { - return new ActiveMQQueue("test,special"); - } - - @Override - public void testQueuePersistentPreparedAcksAvailableAfterRestartAndRollback() throws Exception { - // super.testQueuePersistentPreparedAcksAvailableAfterRestartAndRollback(); - } - - @Override - public void testQueuePersistentUncommittedAcksLostOnRestart() throws Exception { - // super.testQueuePersistentUncommittedAcksLostOnRestart(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/message/security/MessageAuthenticationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/message/security/MessageAuthenticationTest.java deleted file mode 100644 index 4474867bb6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/message/security/MessageAuthenticationTest.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.activemq.broker.message.security; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.io.IOException; - -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.ConnectionContext; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.Message; -import org.apache.activemq.security.MessageAuthorizationPolicy; -import org.apache.activemq.spring.ConsumerBean; - -/** - * - */ -public class MessageAuthenticationTest extends EmbeddedBrokerTestSupport { - - private Connection connection; - - public void testSendInvalidMessage() throws Exception { - if (connection == null) { - connection = createConnection(); - } - connection.start(); - - ConsumerBean messageList = new ConsumerBean(); - messageList.setVerbose(true); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - Destination destination = new ActiveMQQueue("MyQueue"); - - MessageConsumer c1 = session.createConsumer(destination); - - c1.setMessageListener(messageList); - - MessageProducer producer = session.createProducer(destination); - assertNotNull(producer); - - producer.send(createMessage(session, "invalidBody", "myHeader", "xyz")); - producer.send(createMessage(session, "validBody", "myHeader", "abc")); - - messageList.assertMessagesArrived(1); - assertEquals("validBody", ((TextMessage) messageList.flushMessages().get(0)).getText()); - } - - private javax.jms.Message createMessage(Session session, - String body, - String header, - String value) throws JMSException { - TextMessage msg = session.createTextMessage(body); - msg.setStringProperty(header, value); - return msg; - } - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - answer.setPersistent(false); - answer.setMessageAuthorizationPolicy(new MessageAuthorizationPolicy() { - @Override - public boolean isAllowedToConsume(ConnectionContext context, Message message) { - try { - Object value = message.getProperty("myHeader"); - return "abc".equals(value); - } catch (IOException e) { - System.out.println("Caught: " + e); - e.printStackTrace(); - return false; - } - } - }); - answer.addConnector(bindAddress); - return answer; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/out-of-order-broker-elements.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/out-of-order-broker-elements.xml deleted file mode 100644 index 245d946f50..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/out-of-order-broker-elements.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/partition/SpringPartitionBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/partition/SpringPartitionBrokerTest.java deleted file mode 100644 index f419967884..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/partition/SpringPartitionBrokerTest.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.activemq.broker.partition; - -import junit.framework.TestCase; - -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.partition.PartitionBrokerPlugin; -import org.apache.activemq.partition.dto.Partitioning; - -/** - */ -public class SpringPartitionBrokerTest extends TestCase { - - public void testCreatePartitionBroker() throws Exception { - - BrokerService broker = BrokerFactory.createBroker("xbean:activemq-partition.xml"); - assertEquals(1, broker.getPlugins().length); - PartitionBrokerPlugin plugin = (PartitionBrokerPlugin) broker.getPlugins()[0]; - Partitioning config = plugin.getConfig(); - assertEquals(2, config.getBrokers().size()); - - String json = "{\n" + - " \"by_client_id\":{\n" + - " \"client1\":{\"ids\":[\"broker1\"]},\n" + - " \"client2\":{\"ids\":[\"broker1\",\"broker2\"]}\n" + - " },\n" + - " \"brokers\":{\n" + - " \"broker1\":\"tcp://localhost:61616\",\n" + - " \"broker2\":\"tcp://localhost:61616\"\n" + - " }\n" + - "}"; - Partitioning expected = Partitioning.MAPPER.readValue(json, Partitioning.class); - assertEquals(expected.toString(), config.toString()); - - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer0Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer0Test.java deleted file mode 100644 index c6c04abd49..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer0Test.java +++ /dev/null @@ -1,177 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.policy; - -import javax.jms.ConnectionFactory; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.Session; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.AbortSlowAckConsumerStrategy; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -@RunWith(value = Parameterized.class) -public class AbortSlowAckConsumer0Test extends AbortSlowConsumer0Test { - - private static final Logger LOG = LoggerFactory.getLogger(AbortSlowAckConsumer0Test.class); - protected long maxTimeSinceLastAck = 5 * 1000; - - AbortSlowAckConsumerStrategy strategy; - - public AbortSlowAckConsumer0Test(Boolean isTopic) { - super(isTopic); - } - - @Override - protected AbortSlowAckConsumerStrategy createSlowConsumerStrategy() { - AbortSlowAckConsumerStrategy strategy = new AbortSlowAckConsumerStrategy(); - strategy.setAbortConnection(abortConnection); - strategy.setCheckPeriod(checkPeriod); - strategy.setMaxSlowDuration(maxSlowDuration); - strategy.setMaxTimeSinceLastAck(maxTimeSinceLastAck); - - return strategy; - } - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - PolicyEntry policy = new PolicyEntry(); - - strategy = createSlowConsumerStrategy(); - underTest = strategy; - - policy.setSlowConsumerStrategy(strategy); - policy.setQueuePrefetch(10); - policy.setTopicPrefetch(10); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); - return broker; - } - - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - factory.getPrefetchPolicy().setAll(1); - return factory; - } - - @Override - @Test - public void testSlowConsumerIsAbortedViaJmx() throws Exception { - strategy.setMaxTimeSinceLastAck(500); // so jmx does the abort - super.testSlowConsumerIsAbortedViaJmx(); - } - - @Test - public void testZeroPrefetchConsumerIsAborted() throws Exception { - strategy.setMaxTimeSinceLastAck(2000); // Make it shorter - - ActiveMQConnection conn = (ActiveMQConnection) createConnectionFactory().createConnection(); - conn.setExceptionListener(this); - connections.add(conn); - - Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); - final MessageConsumer consumer = sess.createConsumer(destination); - assertNotNull(consumer); - conn.start(); - startProducers(destination, 20); - - Message message = consumer.receive(5000); - assertNotNull(message); - - TimeUnit.SECONDS.sleep(15); - - try { - consumer.receive(5000); - fail("Slow consumer not aborted."); - } catch (Exception ex) { - } - } - - @Test - public void testIdleConsumerCanBeAbortedNoMessages() throws Exception { - strategy.setIgnoreIdleConsumers(false); - strategy.setMaxTimeSinceLastAck(2000); // Make it shorter - - ActiveMQConnection conn = (ActiveMQConnection) createConnectionFactory().createConnection(); - conn.setExceptionListener(this); - connections.add(conn); - - Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); - final MessageConsumer consumer = sess.createConsumer(destination); - assertNotNull(consumer); - conn.start(); - - startProducers(destination, 1); - - Message message = consumer.receive(5000); - assertNotNull(message); - - // Consumer needs to be closed before the receive call. - TimeUnit.SECONDS.sleep(15); - - try { - consumer.receive(5000); - fail("Idle consumer not aborted."); - } catch (Exception ex) { - } - } - - @Test - public void testIdleConsumerCanBeAborted() throws Exception { - strategy.setIgnoreIdleConsumers(false); - strategy.setMaxTimeSinceLastAck(2000); // Make it shorter - - ActiveMQConnection conn = (ActiveMQConnection) createConnectionFactory().createConnection(); - conn.setExceptionListener(this); - connections.add(conn); - - Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); - final MessageConsumer consumer = sess.createConsumer(destination); - assertNotNull(consumer); - conn.start(); - startProducers(destination, 1); - - Message message = consumer.receive(5000); - assertNotNull(message); - message.acknowledge(); - - // Consumer needs to be closed before the receive call. - TimeUnit.SECONDS.sleep(15); - - try { - consumer.receive(5000); - fail("Idle consumer not aborted."); - } catch (Exception ex) { - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer1Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer1Test.java deleted file mode 100644 index fd1558be23..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer1Test.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.activemq.broker.policy; - -import javax.jms.ConnectionFactory; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.AbortSlowAckConsumerStrategy; -import org.apache.activemq.broker.region.policy.AbortSlowConsumerStrategy; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(value = Parameterized.class) -public class AbortSlowAckConsumer1Test extends AbortSlowConsumer1Test { - - protected long maxTimeSinceLastAck = 5 * 1000; - - public AbortSlowAckConsumer1Test(Boolean abortConnection, Boolean topic) { - super(abortConnection, topic); - } - - @Override - protected AbortSlowConsumerStrategy createSlowConsumerStrategy() { - return new AbortSlowConsumerStrategy(); - } - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - PolicyEntry policy = new PolicyEntry(); - - AbortSlowAckConsumerStrategy strategy = new AbortSlowAckConsumerStrategy(); - strategy.setAbortConnection(abortConnection); - strategy.setCheckPeriod(checkPeriod); - strategy.setMaxSlowDuration(maxSlowDuration); - strategy.setMaxTimeSinceLastAck(maxTimeSinceLastAck); - - policy.setSlowConsumerStrategy(strategy); - policy.setQueuePrefetch(10); - policy.setTopicPrefetch(10); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); - return broker; - } - - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - factory.getPrefetchPolicy().setAll(1); - return factory; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer2Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer2Test.java deleted file mode 100644 index 1f896ec70c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer2Test.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.activemq.broker.policy; - -import javax.jms.ConnectionFactory; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.AbortSlowAckConsumerStrategy; -import org.apache.activemq.broker.region.policy.AbortSlowConsumerStrategy; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(value = Parameterized.class) -public class AbortSlowAckConsumer2Test extends AbortSlowConsumer2Test { - - protected long maxTimeSinceLastAck = 5 * 1000; - - public AbortSlowAckConsumer2Test(Boolean topic) { - super(topic); - } - - @Override - protected AbortSlowConsumerStrategy createSlowConsumerStrategy() { - return new AbortSlowConsumerStrategy(); - } - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - PolicyEntry policy = new PolicyEntry(); - - AbortSlowAckConsumerStrategy strategy = new AbortSlowAckConsumerStrategy(); - strategy.setAbortConnection(abortConnection); - strategy.setCheckPeriod(checkPeriod); - strategy.setMaxSlowDuration(maxSlowDuration); - strategy.setMaxTimeSinceLastAck(maxTimeSinceLastAck); - - policy.setSlowConsumerStrategy(strategy); - policy.setQueuePrefetch(10); - policy.setTopicPrefetch(10); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); - return broker; - } - - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - factory.getPrefetchPolicy().setAll(1); - return factory; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer0Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer0Test.java deleted file mode 100644 index af96651ef6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer0Test.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.activemq.broker.policy; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageConsumer; -import javax.jms.Session; -import javax.management.InstanceNotFoundException; -import javax.management.ObjectName; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.TabularData; -import java.lang.reflect.UndeclaredThrowableException; -import java.util.Arrays; -import java.util.Collection; -import java.util.Map.Entry; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ActiveMQMessageConsumer; -import org.apache.activemq.ActiveMQPrefetchPolicy; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.broker.jmx.AbortSlowConsumerStrategyViewMBean; -import org.apache.activemq.broker.jmx.DestinationViewMBean; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.util.MessageIdList; -import org.apache.activemq.util.SocketProxy; -import org.apache.activemq.util.Wait; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -@RunWith(value = Parameterized.class) -public class AbortSlowConsumer0Test extends AbortSlowConsumerBase { - - private static final Logger LOG = LoggerFactory.getLogger(AbortSlowConsumer0Test.class); - - @Parameterized.Parameters(name = "isTopic({0})") - public static Collection getTestParameters() { - return Arrays.asList(new Object[][]{{Boolean.TRUE}, {Boolean.FALSE}}); - } - - public AbortSlowConsumer0Test(Boolean isTopic) { - this.topic = isTopic; - } - - @Test - public void testRegularConsumerIsNotAborted() throws Exception { - startConsumers(destination); - for (Connection c : connections) { - c.setExceptionListener(this); - } - startProducers(destination, 100); - allMessagesList.waitForMessagesToArrive(10); - allMessagesList.assertAtLeastMessagesReceived(10); - } - - @Test - public void testSlowConsumerIsAbortedViaJmx() throws Exception { - underTest.setMaxSlowDuration(60 * 1000); // so jmx does the abort - startConsumers(withPrefetch(2, destination)); - Entry consumertoAbort = consumers.entrySet().iterator().next(); - consumertoAbort.getValue().setProcessingDelay(8 * 1000); - for (Connection c : connections) { - c.setExceptionListener(this); - } - startProducers(destination, 100); - - consumertoAbort.getValue().assertMessagesReceived(1); - - ActiveMQDestination amqDest = (ActiveMQDestination) destination; - ObjectName destinationViewMBean = new ObjectName("org.apache.activemq:destinationType=" + - (amqDest.isTopic() ? "Topic" : "Queue") + ",destinationName=" + amqDest.getPhysicalName() + ",type=Broker,brokerName=localhost"); - - DestinationViewMBean queue = (DestinationViewMBean) broker.getManagementContext().newProxyInstance(destinationViewMBean, DestinationViewMBean.class, true); - ObjectName slowConsumerPolicyMBeanName = queue.getSlowConsumerStrategy(); - - assertNotNull(slowConsumerPolicyMBeanName); - - AbortSlowConsumerStrategyViewMBean abortPolicy = (AbortSlowConsumerStrategyViewMBean) broker.getManagementContext().newProxyInstance(slowConsumerPolicyMBeanName, AbortSlowConsumerStrategyViewMBean.class, true); - - TimeUnit.SECONDS.sleep(3); - - TabularData slowOnes = abortPolicy.getSlowConsumers(); - assertEquals("one slow consumers", 1, slowOnes.size()); - - LOG.info("slow ones:" + slowOnes); - - CompositeData slowOne = (CompositeData) slowOnes.values().iterator().next(); - LOG.info("Slow one: " + slowOne); - - assertTrue("we have an object name", slowOne.get("subscription") instanceof ObjectName); - abortPolicy.abortConsumer((ObjectName) slowOne.get("subscription")); - - consumertoAbort.getValue().assertAtMostMessagesReceived(1); - - slowOnes = abortPolicy.getSlowConsumers(); - assertEquals("no slow consumers left", 0, slowOnes.size()); - - // verify mbean gone with destination - broker.getAdminView().removeTopic(amqDest.getPhysicalName()); - - try { - abortPolicy.getSlowConsumers(); - fail("expect not found post destination removal"); - } catch (UndeclaredThrowableException expected) { - assertTrue("correct exception: " + expected.getCause(), expected.getCause() instanceof InstanceNotFoundException); - } - } - - private Destination withPrefetch(int i, Destination destination) { - String destWithPrefetch = ((ActiveMQDestination) destination).getPhysicalName() + "?consumer.prefetchSize=" + i; - return topic ? new ActiveMQTopic(destWithPrefetch) : new ActiveMQQueue(destWithPrefetch); - } - - @Test - public void testOnlyOneSlowConsumerIsAborted() throws Exception { - consumerCount = 10; - startConsumers(destination); - Entry consumertoAbort = consumers.entrySet().iterator().next(); - consumertoAbort.getValue().setProcessingDelay(8 * 1000); - for (Connection c : connections) { - c.setExceptionListener(this); - } - startProducers(destination, 100); - - allMessagesList.waitForMessagesToArrive(99); - allMessagesList.assertAtLeastMessagesReceived(99); - - consumertoAbort.getValue().assertMessagesReceived(1); - TimeUnit.SECONDS.sleep(5); - consumertoAbort.getValue().assertAtMostMessagesReceived(1); - } - - @Test - public void testAbortAlreadyClosingConsumers() throws Exception { - consumerCount = 1; - startConsumers(withPrefetch(2, destination)); - for (MessageIdList list : consumers.values()) { - list.setProcessingDelay(6 * 1000); - } - for (Connection c : connections) { - c.setExceptionListener(this); - } - startProducers(destination, 100); - allMessagesList.waitForMessagesToArrive(consumerCount); - - for (MessageConsumer consumer : consumers.keySet()) { - LOG.info("closing consumer: " + consumer); - /// will block waiting for on message till 6secs expire - consumer.close(); - } - } - - @Test - public void testAbortConsumerOnDeadConnection() throws Exception { - TransportConnector transportConnector = broker.addConnector("tcp://0.0.0.0:0"); - transportConnector.setBrokerService(broker); - transportConnector.setTaskRunnerFactory(broker.getTaskRunnerFactory()); - transportConnector.start(); - SocketProxy socketProxy = new SocketProxy(transportConnector.getPublishableConnectURI()); - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(socketProxy.getUrl()); - ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); - prefetchPolicy.setAll(4); - connectionFactory.setPrefetchPolicy(prefetchPolicy); - Connection c = connectionFactory.createConnection(); - connections.add(c); - c.start(); - Session session = c.createSession(false, Session.CLIENT_ACKNOWLEDGE); - final ActiveMQMessageConsumer messageconsumer = (ActiveMQMessageConsumer) session.createConsumer(destination); - startProducers(destination, 10); - - messageconsumer.receive(4000).acknowledge(); - assertNotNull(messageconsumer.receive(4000)); - assertNotNull(messageconsumer.receive(4000)); - assertNotNull(messageconsumer.receive(4000)); - - // close control command won't get through - socketProxy.pause(); - - ActiveMQDestination amqDest = (ActiveMQDestination) destination; - ObjectName destinationViewMBean = new ObjectName("org.apache.activemq:destinationType=" + - (amqDest.isTopic() ? "Topic" : "Queue") + ",destinationName=" + amqDest.getPhysicalName() + ",type=Broker,brokerName=localhost"); - - final DestinationViewMBean destView = (DestinationViewMBean) broker.getManagementContext().newProxyInstance(destinationViewMBean, DestinationViewMBean.class, true); - - assertTrue("Consumer gone from broker view", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("DestView {} consumerCount {}", destView, destView.getConsumerCount()); - return 0 == destView.getConsumerCount(); - } - })); - - socketProxy.goOn(); - - assertTrue("consumer was closed", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - boolean closed = false; - try { - messageconsumer.receive(400); - } catch (javax.jms.IllegalStateException expected) { - closed = expected.toString().contains("closed"); - } - return closed; - } - })); - } - - @Override - public void onException(JMSException exception) { - exceptions.add(exception); - exception.printStackTrace(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer1Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer1Test.java deleted file mode 100644 index d27408cada..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer1Test.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.activemq.broker.policy; - -import javax.jms.Connection; -import javax.jms.MessageConsumer; -import javax.jms.Session; -import java.util.Arrays; -import java.util.Collection; -import java.util.Map.Entry; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.util.MessageIdList; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertTrue; - -@RunWith(value = Parameterized.class) -public class AbortSlowConsumer1Test extends AbortSlowConsumerBase { - - private static final Logger LOG = LoggerFactory.getLogger(AbortSlowConsumer1Test.class); - - @Parameterized.Parameters(name = "abortConnection({0})-isTopic({1})") - public static Collection getTestParameters() { - return Arrays.asList(new Object[][]{{Boolean.TRUE, Boolean.TRUE}, {Boolean.TRUE, Boolean.FALSE}, {Boolean.FALSE, Boolean.TRUE}, {Boolean.FALSE, Boolean.FALSE}}); - } - - public AbortSlowConsumer1Test(Boolean abortConnection, Boolean topic) { - this.abortConnection = abortConnection; - this.topic = topic; - } - - @Test(timeout = 60 * 1000) - public void testSlowConsumerIsAborted() throws Exception { - startConsumers(destination); - Entry consumertoAbort = consumers.entrySet().iterator().next(); - consumertoAbort.getValue().setProcessingDelay(8 * 1000); - for (Connection c : connections) { - c.setExceptionListener(this); - } - startProducers(destination, 100); - - consumertoAbort.getValue().assertMessagesReceived(1); - TimeUnit.SECONDS.sleep(5); - consumertoAbort.getValue().assertAtMostMessagesReceived(1); - } - - @Test(timeout = 60 * 1000) - public void testAbortAlreadyClosedConsumers() throws Exception { - Connection conn = createConnectionFactory().createConnection(); - conn.setExceptionListener(this); - connections.add(conn); - - Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); - final MessageConsumer consumer = sess.createConsumer(destination); - conn.start(); - startProducers(destination, 20); - TimeUnit.SECONDS.sleep(1); - LOG.info("closing consumer: " + consumer); - consumer.close(); - - TimeUnit.SECONDS.sleep(5); - assertTrue("no exceptions : " + exceptions, exceptions.isEmpty()); - } - - @Test(timeout = 60 * 1000) - public void testAbortAlreadyClosedConnection() throws Exception { - Connection conn = createConnectionFactory().createConnection(); - conn.setExceptionListener(this); - - Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); - sess.createConsumer(destination); - conn.start(); - startProducers(destination, 20); - TimeUnit.SECONDS.sleep(1); - LOG.info("closing connection: " + conn); - conn.close(); - - TimeUnit.SECONDS.sleep(5); - assertTrue("no exceptions : " + exceptions, exceptions.isEmpty()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer2Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer2Test.java deleted file mode 100644 index 4a6e4dbf1f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumer2Test.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.policy; - -import javax.jms.Connection; -import javax.jms.MessageConsumer; -import java.util.Arrays; -import java.util.Collection; -import java.util.Map.Entry; - -import org.apache.activemq.util.MessageIdList; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(value = Parameterized.class) -public class AbortSlowConsumer2Test extends AbortSlowConsumerBase { - - @Parameterized.Parameters(name = "isTopic({0})") - public static Collection getTestParameters() { - return Arrays.asList(new Object[][]{{Boolean.TRUE}, {Boolean.FALSE}}); - } - - public AbortSlowConsumer2Test(Boolean isTopic) { - this.topic = isTopic; - } - - @Test(timeout = 60 * 1000) - public void testLittleSlowConsumerIsNotAborted() throws Exception { - startConsumers(destination); - Entry consumertoAbort = consumers.entrySet().iterator().next(); - consumertoAbort.getValue().setProcessingDelay(500); - for (Connection c : connections) { - c.setExceptionListener(this); - } - startProducers(destination, 12); - allMessagesList.waitForMessagesToArrive(10); - allMessagesList.assertAtLeastMessagesReceived(10); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumerBase.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumerBase.java deleted file mode 100644 index a12868d478..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowConsumerBase.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.policy; - -import javax.jms.ExceptionListener; -import javax.jms.JMSException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.activemq.JmsMultipleClientsTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.AbortSlowConsumerStrategy; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.junit.Before; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class AbortSlowConsumerBase extends JmsMultipleClientsTestSupport implements ExceptionListener { - - private static final Logger LOG = LoggerFactory.getLogger(AbortSlowConsumerBase.class); - - protected AbortSlowConsumerStrategy underTest; - protected boolean abortConnection = false; - protected long checkPeriod = 2 * 1000; - protected long maxSlowDuration = 5 * 1000; - protected final List exceptions = new ArrayList<>(); - - @Override - @Before - public void setUp() throws Exception { - exceptions.clear(); - topic = true; - underTest = createSlowConsumerStrategy(); - super.setUp(); - createDestination(); - } - - protected AbortSlowConsumerStrategy createSlowConsumerStrategy() { - return new AbortSlowConsumerStrategy(); - } - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - PolicyEntry policy = new PolicyEntry(); - underTest.setAbortConnection(abortConnection); - underTest.setCheckPeriod(checkPeriod); - underTest.setMaxSlowDuration(maxSlowDuration); - - policy.setSlowConsumerStrategy(underTest); - policy.setQueuePrefetch(10); - policy.setTopicPrefetch(10); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); - return broker; - } - - @Override - public void onException(JMSException exception) { - exceptions.add(exception); - exception.printStackTrace(); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DeadLetterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DeadLetterTest.java deleted file mode 100644 index 665026c251..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DeadLetterTest.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.activemq.broker.policy; - -import javax.jms.Destination; -import javax.jms.Message; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.RedeliveryPolicy; -import org.apache.activemq.command.ActiveMQQueue; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * - */ -public class DeadLetterTest extends DeadLetterTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(DeadLetterTest.class); - - protected int rollbackCount; - - @Override - protected void doTest() throws Exception { - connection.start(); - - ActiveMQConnection amqConnection = (ActiveMQConnection) connection; - rollbackCount = amqConnection.getRedeliveryPolicy().getMaximumRedeliveries() + 1; - LOG.info("Will redeliver messages: " + rollbackCount + " times"); - - makeConsumer(); - makeDlqConsumer(); - - sendMessages(); - - // now lets receive and rollback N times - for (int i = 0; i < messageCount; i++) { - consumeAndRollback(i); - } - - for (int i = 0; i < messageCount; i++) { - Message msg = dlqConsumer.receive(1000); - assertMessage(msg, i); - assertNotNull("Should be a DLQ message for loop: " + i, msg); - } - session.commit(); - } - - protected void consumeAndRollback(int messageCounter) throws Exception { - for (int i = 0; i < rollbackCount; i++) { - Message message = consumer.receive(5000); - assertNotNull("No message received for message: " + messageCounter + " and rollback loop: " + i, message); - assertMessage(message, messageCounter); - - session.rollback(); - } - LOG.info("Rolled back: " + rollbackCount + " times"); - } - - @Override - protected void setUp() throws Exception { - transactedMode = true; - super.setUp(); - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory answer = super.createConnectionFactory(); - RedeliveryPolicy policy = new RedeliveryPolicy(); - policy.setMaximumRedeliveries(3); - policy.setBackOffMultiplier((short) 1); - policy.setInitialRedeliveryDelay(10); - policy.setUseExponentialBackOff(false); - answer.setRedeliveryPolicy(policy); - return answer; - } - - @Override - protected Destination createDlqDestination() { - return new ActiveMQQueue("ActiveMQ.DLQ"); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DeadLetterTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DeadLetterTestSupport.java deleted file mode 100644 index 4a85a0f12a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DeadLetterTestSupport.java +++ /dev/null @@ -1,213 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.policy; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.QueueBrowser; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.jms.Topic; - -import org.apache.activemq.TestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.DestinationStatistics; -import org.apache.activemq.broker.region.RegionBroker; -import org.apache.activemq.broker.region.policy.DeadLetterStrategy; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public abstract class DeadLetterTestSupport extends TestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(DeadLetterTestSupport.class); - - protected int messageCount = 10; - protected long timeToLive; - protected Connection connection; - protected Session session; - protected MessageConsumer consumer; - protected MessageProducer producer; - protected int deliveryMode = DeliveryMode.PERSISTENT; - protected boolean durableSubscriber; - protected Destination dlqDestination; - protected MessageConsumer dlqConsumer; - protected QueueBrowser dlqBrowser; - protected BrokerService broker; - protected boolean transactedMode; - protected int acknowledgeMode = Session.CLIENT_ACKNOWLEDGE; - private Destination destination; - - @Override - protected void setUp() throws Exception { - super.setUp(); - broker = createBroker(); - broker.start(); - connection = createConnection(); - connection.setClientID(createClientId()); - - session = connection.createSession(transactedMode, acknowledgeMode); - connection.start(); - } - - protected String createClientId() { - return toString(); - } - - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - if (broker != null) { - broker.stop(); - } - } - - protected abstract void doTest() throws Exception; - - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setPersistent(false); - PolicyEntry policy = new PolicyEntry(); - DeadLetterStrategy defaultDeadLetterStrategy = policy.getDeadLetterStrategy(); - if (defaultDeadLetterStrategy != null) { - defaultDeadLetterStrategy.setProcessNonPersistent(true); - } - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); - return broker; - } - - protected void makeConsumer() throws JMSException { - Destination destination = getDestination(); - LOG.info("Consuming from: " + destination); - if (durableSubscriber) { - consumer = session.createDurableSubscriber((Topic) destination, destination.toString()); - } else { - consumer = session.createConsumer(destination); - } - } - - protected void makeDlqConsumer() throws Exception { - dlqDestination = createDlqDestination(); - - LOG.info("Consuming from dead letter on: " + dlqDestination); - dlqConsumer = session.createConsumer(dlqDestination); - } - - protected void makeDlqBrowser() throws JMSException { - dlqDestination = createDlqDestination(); - - LOG.info("Browsing dead letter on: " + dlqDestination); - dlqBrowser = session.createBrowser((Queue) dlqDestination); - } - - protected void sendMessages() throws JMSException { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(getDestination()); - producer.setDeliveryMode(deliveryMode); - producer.setTimeToLive(timeToLive); - - LOG.info("Sending " + messageCount + " messages to: " + getDestination()); - for (int i = 0; i < messageCount; i++) { - Message message = createMessage(session, i); - producer.send(message); - } - } - - protected TextMessage createMessage(Session session, int i) throws JMSException { - return session.createTextMessage(getMessageText(i)); - } - - protected String getMessageText(int i) { - return "message: " + i; - } - - protected void assertMessage(Message message, int i) throws Exception { - LOG.info("Received message: " + message); - assertNotNull("No message received for index: " + i, message); - assertTrue("Should be a TextMessage not: " + message, message instanceof TextMessage); - TextMessage textMessage = (TextMessage) message; - assertEquals("text of message: " + i, getMessageText(i), textMessage.getText()); - } - - protected abstract Destination createDlqDestination(); - - public void testTransientTopicMessage() throws Exception { - super.topic = true; - deliveryMode = DeliveryMode.NON_PERSISTENT; - durableSubscriber = true; - doTest(); - } - - public void testDurableTopicMessage() throws Exception { - super.topic = true; - deliveryMode = DeliveryMode.PERSISTENT; - durableSubscriber = true; - doTest(); - } - - public void testTransientQueueMessage() throws Exception { - super.topic = false; - deliveryMode = DeliveryMode.NON_PERSISTENT; - durableSubscriber = false; - doTest(); - validateConsumerPrefetch(this.getDestinationString(), 0); - } - - public void testDurableQueueMessage() throws Exception { - super.topic = false; - deliveryMode = DeliveryMode.PERSISTENT; - durableSubscriber = false; - doTest(); - validateConsumerPrefetch(this.getDestinationString(), 0); - } - - public Destination getDestination() { - if (destination == null) { - destination = createDestination(); - } - return destination; - } - - private void validateConsumerPrefetch(String destination, long expectedCount) { - try { - Thread.sleep(100); - } catch (InterruptedException e) { - } - RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); - for (org.apache.activemq.broker.region.Destination dest : regionBroker.getQueueRegion().getDestinationMap().values()) { - if (dest.getName().equals(destination)) { - DestinationStatistics stats = dest.getDestinationStatistics(); - LOG.info(">>>> inflight for : " + dest.getName() + ": " + stats.getInflight().getCount()); - assertEquals("inflight for: " + dest.getName() + ": " + stats.getInflight().getCount() + " matches", expectedCount, stats.getInflight().getCount()); - } - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DestinationCursorConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DestinationCursorConfigTest.java deleted file mode 100644 index 54013358e0..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DestinationCursorConfigTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.policy; - -import org.apache.activemq.TestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PendingQueueMessageStoragePolicy; -import org.apache.activemq.broker.region.policy.PendingSubscriberMessageStoragePolicy; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.VMPendingQueueMessageStoragePolicy; -import org.apache.activemq.broker.region.policy.VMPendingSubscriberMessageStoragePolicy; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.xbean.BrokerFactoryBean; -import org.springframework.core.io.ClassPathResource; - -/** - * - */ -public class DestinationCursorConfigTest extends TestSupport { - - protected BrokerService broker; - - @Override - protected void setUp() throws Exception { - broker = createBroker(); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - broker.stop(); - super.tearDown(); - } - - protected BrokerService createBroker() throws Exception { - BrokerFactoryBean factory = new BrokerFactoryBean(new ClassPathResource("org/apache/activemq/broker/policy/cursor.xml")); - factory.afterPropertiesSet(); - BrokerService answer = factory.getBroker(); - return answer; - } - - public void testQueueConfiguration() throws Exception { - super.topic = false; - ActiveMQDestination destination = (ActiveMQDestination) createDestination("org.apache.foo"); - PolicyEntry entry = broker.getDestinationPolicy().getEntryFor(destination); - PendingQueueMessageStoragePolicy policy = entry.getPendingQueuePolicy(); - assertNotNull(policy); - assertTrue("Policy is: " + policy, policy instanceof VMPendingQueueMessageStoragePolicy); - } - - public void testTopicConfiguration() throws Exception { - super.topic = true; - ActiveMQDestination destination = (ActiveMQDestination) createDestination("org.apache.foo"); - PolicyEntry entry = broker.getDestinationPolicy().getEntryFor(destination); - PendingSubscriberMessageStoragePolicy policy = entry.getPendingSubscriberPolicy(); - assertNotNull(policy); - assertFalse(entry.isProducerFlowControl()); - assertTrue(entry.getMemoryLimit() == (1024 * 1024)); - assertTrue("subscriberPolicy is: " + policy, policy instanceof VMPendingSubscriberMessageStoragePolicy); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DiscardingDeadLetterPolicyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DiscardingDeadLetterPolicyTest.java deleted file mode 100644 index f28d8f0c9a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/DiscardingDeadLetterPolicyTest.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.activemq.broker.policy; - -import javax.jms.Message; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.DeadLetterStrategy; -import org.apache.activemq.broker.region.policy.DiscardingDeadLetterStrategy; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class DiscardingDeadLetterPolicyTest extends DeadLetterTest { - - private static final Logger LOG = LoggerFactory.getLogger(DiscardingDeadLetterPolicyTest.class); - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - - PolicyEntry policy = new PolicyEntry(); - DeadLetterStrategy strategy = new DiscardingDeadLetterStrategy(); - strategy.setProcessNonPersistent(true); - policy.setDeadLetterStrategy(strategy); - - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - - broker.setDestinationPolicy(pMap); - - return broker; - } - - @Override - protected void doTest() throws Exception { - connection.start(); - - ActiveMQConnection amqConnection = (ActiveMQConnection) connection; - rollbackCount = amqConnection.getRedeliveryPolicy().getMaximumRedeliveries() + 1; - LOG.info("Will redeliver messages: " + rollbackCount + " times"); - - makeConsumer(); - makeDlqConsumer(); - - sendMessages(); - - // now lets receive and rollback N times - for (int i = 0; i < messageCount; i++) { - consumeAndRollback(i); - } - - for (int i = 0; i < messageCount; i++) { - Message msg = dlqConsumer.receive(1000); - assertNull("Should not be a DLQ message for loop: " + i, msg); - } - session.commit(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/IndividualDeadLetterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/IndividualDeadLetterTest.java deleted file mode 100644 index b6e287a8ce..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/IndividualDeadLetterTest.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.activemq.broker.policy; - -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.Queue; -import java.util.Enumeration; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.DeadLetterStrategy; -import org.apache.activemq.broker.region.policy.IndividualDeadLetterStrategy; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQQueue; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class IndividualDeadLetterTest extends DeadLetterTest { - - private static final Logger LOG = LoggerFactory.getLogger(IndividualDeadLetterTest.class); - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - - PolicyEntry policy = new PolicyEntry(); - DeadLetterStrategy strategy = new IndividualDeadLetterStrategy(); - strategy.setProcessNonPersistent(true); - policy.setDeadLetterStrategy(strategy); - - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - - broker.setDestinationPolicy(pMap); - - return broker; - } - - @Override - protected Destination createDlqDestination() { - String prefix = topic ? "ActiveMQ.DLQ.Topic." : "ActiveMQ.DLQ.Queue."; - return new ActiveMQQueue(prefix + getClass().getName() + "." + getName()); - } - - public void testDLQBrowsing() throws Exception { - super.topic = false; - deliveryMode = DeliveryMode.PERSISTENT; - durableSubscriber = false; - messageCount = 1; - - connection.start(); - - ActiveMQConnection amqConnection = (ActiveMQConnection) connection; - rollbackCount = amqConnection.getRedeliveryPolicy().getMaximumRedeliveries() + 1; - LOG.info("Will redeliver messages: " + rollbackCount + " times"); - - sendMessages(); - - // now lets receive and rollback N times - for (int i = 0; i < rollbackCount; i++) { - makeConsumer(); - Message message = consumer.receive(5000); - assertNotNull("No message received: ", message); - - session.rollback(); - LOG.info("Rolled back: " + rollbackCount + " times"); - consumer.close(); - } - - makeDlqBrowser(); - browseDlq(); - dlqBrowser.close(); - session.close(); - Thread.sleep(1000); - session = connection.createSession(transactedMode, acknowledgeMode); - Queue testQueue = new ActiveMQQueue("ActiveMQ.DLQ.Queue.ActiveMQ.DLQ.Queue." + getClass().getName() + "." + getName()); - MessageConsumer testConsumer = session.createConsumer(testQueue); - assertNull("The message shouldn't be sent to another DLQ", testConsumer.receive(1000)); - - } - - protected void browseDlq() throws Exception { - Enumeration messages = dlqBrowser.getEnumeration(); - while (messages.hasMoreElements()) { - LOG.info("Browsing: " + messages.nextElement()); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/IndividualDeadLetterViaXmlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/IndividualDeadLetterViaXmlTest.java deleted file mode 100644 index 3d0c218114..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/IndividualDeadLetterViaXmlTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.policy; - -import javax.jms.Destination; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.xbean.BrokerFactoryBean; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.ClassPathResource; - -/** - * - * - */ -public class IndividualDeadLetterViaXmlTest extends DeadLetterTest { - - private static final Logger LOG = LoggerFactory.getLogger(IndividualDeadLetterViaXmlTest.class); - - @Override - protected BrokerService createBroker() throws Exception { - BrokerFactoryBean factory = new BrokerFactoryBean(new ClassPathResource("org/apache/activemq/broker/policy/individual-dlq.xml")); - factory.afterPropertiesSet(); - BrokerService answer = factory.getBroker(); - return answer; - } - - @Override - protected Destination createDlqDestination() { - String queueName = "Test.DLQ." + getClass().getName() + "." + getName(); - LOG.info("Using queue name: " + queueName); - return new ActiveMQQueue(queueName); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/MessageGroupConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/MessageGroupConfigTest.java deleted file mode 100644 index 0b93472153..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/MessageGroupConfigTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.policy; - -import org.apache.activemq.TestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.Queue; -import org.apache.activemq.broker.region.group.CachedMessageGroupMap; -import org.apache.activemq.broker.region.group.MessageGroupHashBucket; -import org.apache.activemq.broker.region.group.MessageGroupMap; -import org.apache.activemq.broker.region.group.SimpleMessageGroupMap; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQDestination; - -/** - * - */ -public class MessageGroupConfigTest extends TestSupport { - - protected BrokerService broker; - - @Override - protected void setUp() throws Exception { - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - broker.stop(); - super.tearDown(); - } - - public void testCachedGroupConfiguration() throws Exception { - doTestGroupConfiguration("cached", CachedMessageGroupMap.class); - } - - public void testCachedGroupConfigurationWithCacheSize() throws Exception { - CachedMessageGroupMap result = (CachedMessageGroupMap) doTestGroupConfiguration("cached?cacheSize=10", CachedMessageGroupMap.class); - assertEquals(10, result.getMaximumCacheSize()); - - } - - public void testSimpleGroupConfiguration() throws Exception { - doTestGroupConfiguration("simple", SimpleMessageGroupMap.class); - } - - public void testBucketGroupConfiguration() throws Exception { - doTestGroupConfiguration("bucket", MessageGroupHashBucket.class); - } - - public void testBucketGroupConfigurationWithBucketCount() throws Exception { - MessageGroupHashBucket result = (MessageGroupHashBucket) doTestGroupConfiguration("bucket?bucketCount=2", MessageGroupHashBucket.class); - assertEquals(2, result.getBucketCount()); - } - - public MessageGroupMap doTestGroupConfiguration(String type, Class classType) throws Exception { - broker = new BrokerService(); - - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setMessageGroupMapFactoryType(type); - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(defaultEntry); - broker.setDestinationPolicy(policyMap); - broker.start(); - super.topic = false; - ActiveMQDestination destination = (ActiveMQDestination) createDestination("org.apache.foo"); - Queue brokerDestination = (Queue) broker.getDestination(destination); - - assertNotNull(brokerDestination); - MessageGroupMap messageGroupMap = brokerDestination.getMessageGroupOwners(); - assertNotNull(messageGroupMap); - assertTrue(messageGroupMap.getClass().isAssignableFrom(classType)); - return messageGroupMap; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/MessageListenerDeadLetterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/MessageListenerDeadLetterTest.java deleted file mode 100644 index c7a88ddaed..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/MessageListenerDeadLetterTest.java +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.policy; - -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageListener; -import javax.jms.Session; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.RedeliveryPolicy; -import org.apache.activemq.command.ActiveMQQueue; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MessageListenerDeadLetterTest extends DeadLetterTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(MessageListenerDeadLetterTest.class); - - private int rollbackCount; - - private Session dlqSession; - - private final Error[] error = new Error[1]; - - @Override - protected void doTest() throws Exception { - messageCount = 200; - connection.start(); - - ActiveMQConnection amqConnection = (ActiveMQConnection) connection; - rollbackCount = amqConnection.getRedeliveryPolicy().getMaximumRedeliveries() + 1; - LOG.info("Will redeliver messages: " + rollbackCount + " times"); - - makeConsumer(); - makeDlqConsumer(); - - sendMessages(); - - // now lets receive and rollback N times - int maxRollbacks = messageCount * rollbackCount; - consumer.setMessageListener(new RollbackMessageListener(maxRollbacks, rollbackCount)); - - for (int i = 0; i < messageCount; i++) { - Message msg = dlqConsumer.receive(4000); - if (error[0] != null) { - // error from message listener - throw error[0]; - } - assertMessage(msg, i); - assertNotNull("Should be a DLQ message for loop: " + i, msg); - } - if (error[0] != null) { - throw error[0]; - } - } - - @Override - protected void makeDlqConsumer() throws JMSException { - dlqDestination = createDlqDestination(); - - LOG.info("Consuming from dead letter on: " + dlqDestination); - dlqConsumer = dlqSession.createConsumer(dlqDestination); - } - - @Override - protected void setUp() throws Exception { - transactedMode = true; - super.setUp(); - dlqSession = connection.createSession(transactedMode, acknowledgeMode); - } - - @Override - protected void tearDown() throws Exception { - dlqConsumer.close(); - dlqSession.close(); - session.close(); - super.tearDown(); - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory answer = super.createConnectionFactory(); - RedeliveryPolicy policy = new RedeliveryPolicy(); - policy.setMaximumRedeliveries(3); - policy.setBackOffMultiplier((short) 1); - policy.setRedeliveryDelay(0); - policy.setInitialRedeliveryDelay(0); - policy.setUseExponentialBackOff(false); - answer.setRedeliveryPolicy(policy); - return answer; - } - - @Override - protected Destination createDlqDestination() { - return new ActiveMQQueue("ActiveMQ.DLQ"); - } - - class RollbackMessageListener implements MessageListener { - - final int maxRollbacks; - - final int deliveryCount; - - AtomicInteger rollbacks = new AtomicInteger(); - - RollbackMessageListener(int c, int delvery) { - maxRollbacks = c; - deliveryCount = delvery; - } - - @Override - public void onMessage(Message message) { - try { - int expectedMessageId = rollbacks.get() / deliveryCount; - LOG.info("expecting messageId: " + expectedMessageId); - assertMessage(message, expectedMessageId); - if (rollbacks.incrementAndGet() > maxRollbacks) { - fail("received too many messages, already done too many rollbacks: " + rollbacks); - } - session.rollback(); - - } catch (Throwable e) { - LOG.error("unexpected exception:" + e, e); - // propagating assertError to execution task will cause a hang - // at shutdown - if (e instanceof Error) { - error[0] = (Error) e; - } else { - fail("unexpected exception: " + e); - } - - } - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/NoConsumerDeadLetterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/NoConsumerDeadLetterTest.java deleted file mode 100644 index 5761400b07..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/NoConsumerDeadLetterTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.policy; - -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.jms.Topic; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.advisory.AdvisorySupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQDestination; - -/** - * - */ -public class NoConsumerDeadLetterTest extends DeadLetterTestSupport { - - // lets disable the inapplicable tests - @Override - public void testDurableQueueMessage() throws Exception { - } - - @Override - public void testDurableTopicMessage() throws Exception { - } - - @Override - protected void doTest() throws Exception { - makeDlqConsumer(); - sendMessages(); - - for (int i = 0; i < messageCount; i++) { - Message msg = dlqConsumer.receive(1000); - assertNotNull("Should be a message for loop: " + i, msg); - } - } - - public void testConsumerReceivesMessages() throws Exception { - this.topic = false; - ActiveMQConnectionFactory factory = createConnectionFactory(); - connection = factory.createConnection(); - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(getDestination()); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - - Topic advisoryTopic = AdvisorySupport.getNoQueueConsumersAdvisoryTopic(getDestination()); - MessageConsumer advisoryConsumer = session.createConsumer(advisoryTopic); - - TextMessage msg = session.createTextMessage("Message: x"); - producer.send(msg); - - Message advisoryMessage = advisoryConsumer.receive(1000); - assertNotNull("Advisory message not received", advisoryMessage); - - Thread.sleep(1000); - - factory = createConnectionFactory(); - connection = factory.createConnection(); - connection.start(); - - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageConsumer consumer = session.createConsumer(getDestination()); - Message received = consumer.receive(1000); - assertNotNull("Message not received", received); - } - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - - PolicyEntry policy = new PolicyEntry(); - policy.setSendAdvisoryIfNoConsumers(true); - - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - - broker.setDestinationPolicy(pMap); - - return broker; - } - - @Override - protected Destination createDlqDestination() { - if (this.topic) { - return AdvisorySupport.getNoTopicConsumersAdvisoryTopic((ActiveMQDestination) getDestination()); - } else { - return AdvisorySupport.getNoQueueConsumersAdvisoryTopic((ActiveMQDestination) getDestination()); - } - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/NoRetryDeadLetterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/NoRetryDeadLetterTest.java deleted file mode 100644 index f7e991db2c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/NoRetryDeadLetterTest.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.activemq.broker.policy; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.RedeliveryPolicy; - -public class NoRetryDeadLetterTest extends DeadLetterTest { - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory connectionFactory = super.createConnectionFactory(); - RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy(); - redeliveryPolicy.setMaximumRedeliveries(0); - connectionFactory.setRedeliveryPolicy(redeliveryPolicy); - return connectionFactory; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/PerDurableConsumerDeadLetterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/PerDurableConsumerDeadLetterTest.java deleted file mode 100644 index d44a49e968..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/PerDurableConsumerDeadLetterTest.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.activemq.broker.policy; - -import javax.jms.Destination; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.IndividualDeadLetterStrategy; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQQueue; - -/** - * for durable subs, allow a dlq per subscriber such that poison messages are not duplicates - * on the dlq and such that rejecting consumers can be identified - * https://issues.apache.org/jira/browse/AMQ-3003 - */ -public class PerDurableConsumerDeadLetterTest extends DeadLetterTest { - - private static final String CLIENT_ID = "george"; - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - - PolicyEntry policy = new PolicyEntry(); - IndividualDeadLetterStrategy strategy = new IndividualDeadLetterStrategy(); - strategy.setProcessNonPersistent(true); - strategy.setDestinationPerDurableSubscriber(true); - policy.setDeadLetterStrategy(strategy); - - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - - broker.setDestinationPolicy(pMap); - - return broker; - } - - @Override - protected String createClientId() { - return CLIENT_ID; - } - - @Override - protected Destination createDlqDestination() { - String prefix = topic ? "ActiveMQ.DLQ.Topic." : "ActiveMQ.DLQ.Queue."; - String destinationName = prefix + getClass().getName() + "." + getName(); - if (durableSubscriber) { - String subName = // connectionId:SubName - CLIENT_ID + ":" + getDestination().toString(); - destinationName += "." + subName; - } - return new ActiveMQQueue(destinationName); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/PriorityNetworkDispatchPolicyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/PriorityNetworkDispatchPolicyTest.java deleted file mode 100644 index f0f42f86fe..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/PriorityNetworkDispatchPolicyTest.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.activemq.broker.policy; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.ConnectionContext; -import org.apache.activemq.broker.region.Subscription; -import org.apache.activemq.broker.region.TopicSubscription; -import org.apache.activemq.broker.region.policy.PriorityNetworkDispatchPolicy; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQMessage; -import org.apache.activemq.command.ConsumerId; -import org.apache.activemq.command.ConsumerInfo; -import org.apache.activemq.command.MessageId; -import org.apache.activemq.usage.SystemUsage; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class PriorityNetworkDispatchPolicyTest { - - PriorityNetworkDispatchPolicy underTest = new PriorityNetworkDispatchPolicy(); - SystemUsage usageManager = new SystemUsage(); - ConsumerInfo info = new ConsumerInfo(); - ActiveMQMessage node = new ActiveMQMessage(); - ConsumerId id = new ConsumerId(); - ConnectionContext context = new ConnectionContext(); - BrokerService brokerService = new BrokerService(); - - @Before - public void init() throws Exception { - info.setDestination(ActiveMQDestination.createDestination("test", ActiveMQDestination.TOPIC_TYPE)); - info.setConsumerId(id); - info.setNetworkSubscription(true); - info.setNetworkConsumerPath(new ConsumerId[]{id}); - node.setMessageId(new MessageId("test:1:1:1:1")); - } - - @After - public void stopBroker() throws Exception { - brokerService.stop(); - } - - @Test - public void testRemoveLowerPriorityDup() throws Exception { - - List consumers = new ArrayList<>(); - - for (int i = 0; i < 3; i++) { - ConsumerInfo instance = info.copy(); - instance.setPriority((byte) i); - consumers.add(new TopicSubscription(brokerService.getBroker(), context, instance, usageManager)); - } - underTest.dispatch(node, null, consumers); - - long count = 0; - for (Subscription consumer : consumers) { - count += consumer.getEnqueueCounter(); - } - assertEquals("only one sub got message", 1, count); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/RoundRobinDispatchPolicyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/RoundRobinDispatchPolicyTest.java deleted file mode 100644 index 82743d7fd7..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/RoundRobinDispatchPolicyTest.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.activemq.broker.policy; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.MessageConsumer; -import javax.jms.Session; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.QueueSubscriptionTest; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.broker.region.policy.RoundRobinDispatchPolicy; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.BlockJUnit4ClassRunner; - -@RunWith(BlockJUnit4ClassRunner.class) -public class RoundRobinDispatchPolicyTest extends QueueSubscriptionTest { - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - - PolicyEntry policy = new PolicyEntry(); - policy.setDispatchPolicy(new RoundRobinDispatchPolicy()); - - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - - broker.setDestinationPolicy(pMap); - - return broker; - } - - @Override - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersSmallMessagesOnePrefetch() throws Exception { - super.testOneProducerTwoConsumersSmallMessagesOnePrefetch(); - - // Ensure that each consumer should have received at least one message - // We cannot guarantee that messages will be equally divided, since - // prefetch is one - assertEachConsumerReceivedAtLeastXMessages(1); - } - - @Override - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersSmallMessagesLargePrefetch() throws Exception { - super.testOneProducerTwoConsumersSmallMessagesLargePrefetch(); - assertMessagesDividedAmongConsumers(); - } - - @Override - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersLargeMessagesOnePrefetch() throws Exception { - super.testOneProducerTwoConsumersLargeMessagesOnePrefetch(); - - // Ensure that each consumer should have received at least one message - // We cannot guarantee that messages will be equally divided, since - // prefetch is one - assertEachConsumerReceivedAtLeastXMessages(1); - } - - @Override - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersLargeMessagesLargePrefetch() throws Exception { - super.testOneProducerTwoConsumersLargeMessagesLargePrefetch(); - assertMessagesDividedAmongConsumers(); - } - - @Override - @Test(timeout = 60 * 1000) - public void testOneProducerManyConsumersFewMessages() throws Exception { - super.testOneProducerManyConsumersFewMessages(); - - // Since there are more consumers, each consumer should have received at - // most one message only - assertMessagesDividedAmongConsumers(); - } - - @Override - @Test(timeout = 60 * 1000) - public void testOneProducerManyConsumersManyMessages() throws Exception { - super.testOneProducerManyConsumersManyMessages(); - assertMessagesDividedAmongConsumers(); - } - - @Override - @Test(timeout = 60 * 1000) - public void testManyProducersManyConsumers() throws Exception { - super.testManyProducersManyConsumers(); - assertMessagesDividedAmongConsumers(); - } - - @Test(timeout = 60 * 1000) - public void testOneProducerTwoMatchingConsumersOneNotMatchingConsumer() throws Exception { - // Create consumer that won't consume any message - createMessageConsumer(createConnectionFactory().createConnection(), createDestination(), "JMSPriority<1"); - super.testOneProducerTwoConsumersSmallMessagesLargePrefetch(); - assertMessagesDividedAmongConsumers(); - } - - protected MessageConsumer createMessageConsumer(Connection conn, - Destination dest, - String selector) throws Exception { - connections.add(conn); - - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageConsumer consumer = sess.createConsumer(dest, selector); - conn.start(); - - return consumer; - } - - public void assertMessagesDividedAmongConsumers() { - assertEachConsumerReceivedAtLeastXMessages((messageCount * producerCount) / consumerCount); - assertEachConsumerReceivedAtMostXMessages(((messageCount * producerCount) / consumerCount) + 1); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/SecureDLQTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/SecureDLQTest.java deleted file mode 100644 index e7e4f4e9c4..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/SecureDLQTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.policy; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.Message; -import javax.jms.Session; - -import org.apache.activemq.broker.BrokerPlugin; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.filter.DestinationMap; -import org.apache.activemq.security.AuthorizationMap; -import org.apache.activemq.security.AuthorizationPlugin; -import org.apache.activemq.security.DefaultAuthorizationMap; -import org.apache.activemq.security.SimpleAuthorizationMap; -import org.apache.activemq.security.SimpleSecurityBrokerSystemTest; - -import static org.apache.activemq.security.SimpleSecurityBrokerSystemTest.ADMINS; -import static org.apache.activemq.security.SimpleSecurityBrokerSystemTest.USERS; -import static org.apache.activemq.security.SimpleSecurityBrokerSystemTest.WILDCARD; - -public class SecureDLQTest extends DeadLetterTestSupport { - - Connection dlqConnection; - Session dlqSession; - - public static AuthorizationMap createAuthorizationMap() { - DestinationMap readAccess = new DefaultAuthorizationMap(); - readAccess.put(new ActiveMQQueue("TEST"), ADMINS); - readAccess.put(new ActiveMQQueue("TEST"), USERS); - readAccess.put(new ActiveMQQueue("ActiveMQ.DLQ"), ADMINS); - - DestinationMap writeAccess = new DefaultAuthorizationMap(); - writeAccess.put(new ActiveMQQueue("TEST"), ADMINS); - writeAccess.put(new ActiveMQQueue("TEST"), USERS); - writeAccess.put(new ActiveMQQueue("ActiveMQ.DLQ"), ADMINS); - - readAccess.put(new ActiveMQTopic("ActiveMQ.Advisory.>"), WILDCARD); - writeAccess.put(new ActiveMQTopic("ActiveMQ.Advisory.>"), WILDCARD); - - DestinationMap adminAccess = new DefaultAuthorizationMap(); - adminAccess.put(new ActiveMQQueue("TEST"), ADMINS); - adminAccess.put(new ActiveMQQueue("TEST"), USERS); - adminAccess.put(new ActiveMQQueue("ActiveMQ.DLQ"), ADMINS); - adminAccess.put(new ActiveMQTopic("ActiveMQ.Advisory.>"), WILDCARD); - - return new SimpleAuthorizationMap(writeAccess, readAccess, adminAccess); - } - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - AuthorizationPlugin authorizationPlugin = new AuthorizationPlugin(createAuthorizationMap()); - - broker.setPlugins(new BrokerPlugin[]{authorizationPlugin, new SimpleSecurityBrokerSystemTest.SimpleAuthenticationFactory()}); - return broker; - } - - // lets disable the inapplicable tests - @Override - public void testTransientTopicMessage() throws Exception { - } - - @Override - public void testDurableTopicMessage() throws Exception { - } - - @Override - protected void doTest() throws Exception { - timeToLive = 1000; - acknowledgeMode = Session.CLIENT_ACKNOWLEDGE; - makeConsumer(); - sendMessages(); - Thread.sleep(1000); - consumer.close(); - - Thread.sleep(1000); - // this should try to send expired messages to dlq - makeConsumer(); - - makeDlqConsumer(); - for (int i = 0; i < messageCount; i++) { - Message msg = dlqConsumer.receive(1000); - assertMessage(msg, i); - assertNotNull("Should be a DLQ message for loop: " + i, msg); - } - - } - - @Override - public void tearDown() throws Exception { - if (dlqConnection != null) { - dlqConnection.close(); - } - super.tearDown(); - } - - @Override - protected Connection createConnection() throws Exception { - return getConnectionFactory().createConnection("user", "password"); - } - - @Override - protected void makeDlqConsumer() throws Exception { - dlqDestination = createDlqDestination(); - dlqConnection = getConnectionFactory().createConnection("system", "manager"); - dlqConnection.start(); - dlqSession = dlqConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - dlqConsumer = dlqSession.createConsumer(dlqDestination); - } - - @Override - protected Destination createDlqDestination() { - return new ActiveMQQueue("ActiveMQ.DLQ"); - } - - @Override - protected String getDestinationString() { - return "TEST"; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/SimpleDispatchPolicyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/SimpleDispatchPolicyTest.java deleted file mode 100644 index fe183eef84..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/SimpleDispatchPolicyTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.policy; - -import javax.jms.MessageConsumer; -import java.util.Iterator; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.QueueSubscriptionTest; -import org.apache.activemq.broker.region.policy.FixedCountSubscriptionRecoveryPolicy; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.broker.region.policy.SimpleDispatchPolicy; -import org.apache.activemq.util.MessageIdList; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.BlockJUnit4ClassRunner; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -@RunWith(BlockJUnit4ClassRunner.class) -public class SimpleDispatchPolicyTest extends QueueSubscriptionTest { - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - - PolicyEntry policy = new PolicyEntry(); - policy.setDispatchPolicy(new SimpleDispatchPolicy()); - policy.setSubscriptionRecoveryPolicy(new FixedCountSubscriptionRecoveryPolicy()); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - - broker.setDestinationPolicy(pMap); - - return broker; - } - - @Override - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersSmallMessagesLargePrefetch() throws Exception { - super.testOneProducerTwoConsumersSmallMessagesLargePrefetch(); - - // One consumer should have received all messages, and the rest none - // assertOneConsumerReceivedAllMessages(messageCount); - } - - @Override - @Test(timeout = 60 * 1000) - public void testOneProducerTwoConsumersLargeMessagesLargePrefetch() throws Exception { - super.testOneProducerTwoConsumersLargeMessagesLargePrefetch(); - - // One consumer should have received all messages, and the rest none - // assertOneConsumerReceivedAllMessages(messageCount); - } - - public void assertOneConsumerReceivedAllMessages(int messageCount) throws Exception { - boolean found = false; - for (Iterator i = consumers.keySet().iterator(); i.hasNext(); ) { - MessageIdList messageIdList = consumers.get(i.next()); - int count = messageIdList.getMessageCount(); - if (count > 0) { - if (found) { - fail("No other consumers should have received any messages"); - } else { - assertEquals("Consumer should have received all messages.", messageCount, count); - found = true; - } - } - } - - if (!found) { - fail("At least one consumer should have received all messages"); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/StrictOrderDispatchPolicyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/StrictOrderDispatchPolicyTest.java deleted file mode 100644 index c82d94a27c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/StrictOrderDispatchPolicyTest.java +++ /dev/null @@ -1,131 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.policy; - -import javax.jms.MessageConsumer; -import java.util.Iterator; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TopicSubscriptionTest; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.broker.region.policy.StrictOrderDispatchPolicy; -import org.apache.activemq.util.MessageIdList; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.BlockJUnit4ClassRunner; - -import static org.junit.Assert.assertTrue; - -@RunWith(BlockJUnit4ClassRunner.class) -public class StrictOrderDispatchPolicyTest extends TopicSubscriptionTest { - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - - PolicyEntry policy = new PolicyEntry(); - policy.setDispatchPolicy(new StrictOrderDispatchPolicy()); - - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - - broker.setDestinationPolicy(pMap); - - return broker; - } - - @Test - @Override - public void testOneProducerTwoConsumersLargeMessagesOnePrefetch() throws Exception { - super.testOneProducerTwoConsumersLargeMessagesOnePrefetch(); - - assertReceivedMessagesAreOrdered(); - } - - @Test - @Override - public void testOneProducerTwoConsumersSmallMessagesOnePrefetch() throws Exception { - super.testOneProducerTwoConsumersSmallMessagesOnePrefetch(); - - assertReceivedMessagesAreOrdered(); - } - - @Test - @Override - public void testOneProducerTwoConsumersSmallMessagesLargePrefetch() throws Exception { - super.testOneProducerTwoConsumersSmallMessagesLargePrefetch(); - - assertReceivedMessagesAreOrdered(); - } - - @Test - @Override - public void testOneProducerTwoConsumersLargeMessagesLargePrefetch() throws Exception { - super.testOneProducerTwoConsumersLargeMessagesLargePrefetch(); - - assertReceivedMessagesAreOrdered(); - } - - @Test - @Override - public void testOneProducerManyConsumersFewMessages() throws Exception { - super.testOneProducerManyConsumersFewMessages(); - - assertReceivedMessagesAreOrdered(); - } - - @Test - @Override - public void testOneProducerManyConsumersManyMessages() throws Exception { - super.testOneProducerManyConsumersManyMessages(); - - assertReceivedMessagesAreOrdered(); - } - - @Test - @Override - public void testManyProducersOneConsumer() throws Exception { - super.testManyProducersOneConsumer(); - - assertReceivedMessagesAreOrdered(); - } - - @Test - @Override - public void testManyProducersManyConsumers() throws Exception { - super.testManyProducersManyConsumers(); - - assertReceivedMessagesAreOrdered(); - } - - public void assertReceivedMessagesAreOrdered() throws Exception { - // If there is only one consumer, messages is definitely ordered - if (consumers.size() <= 1) { - return; - } - - // Get basis of order - Iterator i = consumers.keySet().iterator(); - MessageIdList messageOrder = consumers.get(i.next()); - - for (; i.hasNext(); ) { - MessageIdList messageIdList = consumers.get(i.next()); - assertTrue("Messages are not ordered.", messageOrder.equals(messageIdList)); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/cursor.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/cursor.xml deleted file mode 100644 index d067a2c72d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/cursor.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/individual-dlq.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/individual-dlq.xml deleted file mode 100644 index e79ea926da..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/individual-dlq.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/DestinationGCTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/DestinationGCTest.java deleted file mode 100644 index 6480c1e721..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/DestinationGCTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.region; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.Session; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.util.Wait; -import org.apache.activemq.util.Wait.Condition; - -public class DestinationGCTest extends EmbeddedBrokerTestSupport { - - ActiveMQQueue queue = new ActiveMQQueue("TEST"); - ActiveMQQueue otherQueue = new ActiveMQQueue("TEST-OTHER"); - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - broker.setDestinations(new ActiveMQDestination[]{queue}); - broker.setSchedulePeriodForDestinationPurge(1000); - broker.setMaxPurgedDestinationsPerSweep(1); - PolicyEntry entry = new PolicyEntry(); - entry.setGcInactiveDestinations(true); - entry.setInactiveTimeoutBeforeGC(3000); - PolicyMap map = new PolicyMap(); - map.setDefaultEntry(entry); - broker.setDestinationPolicy(map); - return broker; - } - - public void testDestinationGCWithActiveConsumers() throws Exception { - assertEquals(1, broker.getAdminView().getQueues().length); - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?create=false"); - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createProducer(otherQueue).close(); - MessageConsumer consumer = session.createConsumer(queue); - consumer.setMessageListener(new MessageListener() { - - @Override - public void onMessage(Message message) { - } - }); - connection.start(); - - TimeUnit.SECONDS.sleep(5); - - assertTrue("After GC runs there should be one Queue.", Wait.waitFor(new Condition() { - @Override - public boolean isSatisified() throws Exception { - return broker.getAdminView().getQueues().length == 1; - } - })); - - connection.close(); - } - - public void testDestinationGc() throws Exception { - assertEquals(1, broker.getAdminView().getQueues().length); - assertTrue("After GC runs the Queue should be empty.", Wait.waitFor(new Condition() { - @Override - public boolean isSatisified() throws Exception { - return broker.getAdminView().getQueues().length == 0; - } - })); - } - - public void testDestinationGcLimit() throws Exception { - - broker.getAdminView().addQueue("TEST1"); - broker.getAdminView().addQueue("TEST2"); - broker.getAdminView().addQueue("TEST3"); - broker.getAdminView().addQueue("TEST4"); - - assertEquals(5, broker.getAdminView().getQueues().length); - Thread.sleep(7000); - int queues = broker.getAdminView().getQueues().length; - assertTrue(queues > 0 && queues < 5); - assertTrue("After GC runs the Queue should be empty.", Wait.waitFor(new Condition() { - @Override - public boolean isSatisified() throws Exception { - return broker.getAdminView().getQueues().length == 0; - } - })); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/DestinationRemoveRestartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/DestinationRemoveRestartTest.java deleted file mode 100644 index d4e52b453f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/DestinationRemoveRestartTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.region; - -import junit.framework.Test; - -import org.apache.activemq.CombinationTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQDestination; - -// from https://issues.apache.org/activemq/browse/AMQ-2216 -public class DestinationRemoveRestartTest extends CombinationTestSupport { - - private final static String destinationName = "TEST"; - public byte destinationType = ActiveMQDestination.QUEUE_TYPE; - BrokerService broker; - - @Override - protected void setUp() throws Exception { - broker = createBroker(); - } - - private BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setUseJmx(false); - broker.setPersistent(true); - broker.setDeleteAllMessagesOnStartup(true); - broker.start(); - return broker; - } - - @Override - protected void tearDown() throws Exception { - broker.stop(); - } - - public void initCombosForTestCheckDestinationRemoveActionAfterRestart() { - addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); - } - - public void testCheckDestinationRemoveActionAfterRestart() throws Exception { - doAddDestination(); - doRemoveDestination(); - broker.stop(); - broker.waitUntilStopped(); - broker = createBroker(); - doCheckRemoveActionAfterRestart(); - } - - public void doAddDestination() throws Exception { - boolean res = false; - - ActiveMQDestination amqDestination = ActiveMQDestination.createDestination(destinationName, destinationType); - broker.getRegionBroker().addDestination(broker.getAdminConnectionContext(), amqDestination, true); - - final ActiveMQDestination[] list = broker.getRegionBroker().getDestinations(); - for (final ActiveMQDestination element : list) { - final Destination destination = broker.getDestination(element); - if (destination.getActiveMQDestination().getPhysicalName().equals(destinationName)) { - res = true; - break; - } - } - - assertTrue("Adding destination Failed", res); - } - - public void doRemoveDestination() throws Exception { - boolean res = true; - - broker.removeDestination(ActiveMQDestination.createDestination(destinationName, destinationType)); - final ActiveMQDestination[] list = broker.getRegionBroker().getDestinations(); - for (final ActiveMQDestination element : list) { - final Destination destination = broker.getDestination(element); - if (destination.getActiveMQDestination().getPhysicalName().equals(destinationName)) { - res = false; - break; - } - } - - assertTrue("Removing destination Failed", res); - } - - public void doCheckRemoveActionAfterRestart() throws Exception { - boolean res = true; - - final ActiveMQDestination[] list = broker.getRegionBroker().getDestinations(); - for (final ActiveMQDestination element : list) { - final Destination destination = broker.getDestination(element); - if (destination.getActiveMQDestination().getPhysicalName().equals(destinationName)) { - res = false; - break; - } - } - - assertTrue("The removed destination is reloaded after restart !", res); - } - - public static Test suite() { - return suite(DestinationRemoveRestartTest.class); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueDuplicatesFromStoreTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueDuplicatesFromStoreTest.java deleted file mode 100644 index 3ac79d4698..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueDuplicatesFromStoreTest.java +++ /dev/null @@ -1,404 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.broker.region; - -import javax.jms.InvalidSelectorException; -import javax.management.ObjectName; -import java.io.IOException; -import java.util.List; -import java.util.Vector; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - -import junit.framework.TestCase; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.ConnectionContext; -import org.apache.activemq.broker.ProducerBrokerExchange; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTextMessage; -import org.apache.activemq.command.ConsumerInfo; -import org.apache.activemq.command.Message; -import org.apache.activemq.command.MessageAck; -import org.apache.activemq.command.MessageDispatchNotification; -import org.apache.activemq.command.MessageId; -import org.apache.activemq.command.MessagePull; -import org.apache.activemq.command.ProducerInfo; -import org.apache.activemq.command.Response; -import org.apache.activemq.filter.MessageEvaluationContext; -import org.apache.activemq.state.ProducerState; -import org.apache.activemq.store.MessageStore; -import org.apache.activemq.store.PersistenceAdapter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author gtully - * @see https://issues.apache.org/activemq/browse/AMQ-2020 - **/ -public class QueueDuplicatesFromStoreTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(QueueDuplicatesFromStoreTest.class); - - ActiveMQQueue destination = new ActiveMQQueue("queue-" + QueueDuplicatesFromStoreTest.class.getSimpleName()); - BrokerService brokerService; - - final static String mesageIdRoot = "11111:22222:"; - final int messageBytesSize = 256; - final String text = new String(new byte[messageBytesSize]); - - final int ackStartIndex = 100; - final int ackWindow = 50; - final int ackBatchSize = 50; - final int fullWindow = 200; - protected int count = 5000; - - @Override - public void setUp() throws Exception { - brokerService = createBroker(); - brokerService.setUseJmx(false); - brokerService.deleteAllMessages(); - brokerService.start(); - } - - protected BrokerService createBroker() throws Exception { - return new BrokerService(); - } - - @Override - public void tearDown() throws Exception { - brokerService.stop(); - } - - public void testNoDuplicateAfterCacheFullAndAckedWithLargeAuditDepth() throws Exception { - doTestNoDuplicateAfterCacheFullAndAcked(1024 * 10); - } - - public void testNoDuplicateAfterCacheFullAndAckedWithSmallAuditDepth() throws Exception { - doTestNoDuplicateAfterCacheFullAndAcked(512); - } - - public void doTestNoDuplicateAfterCacheFullAndAcked(final int auditDepth) throws Exception { - final PersistenceAdapter persistenceAdapter = brokerService.getPersistenceAdapter(); - final MessageStore queueMessageStore = persistenceAdapter.createQueueMessageStore(destination); - final ConnectionContext contextNotInTx = new ConnectionContext(); - final ConsumerInfo consumerInfo = new ConsumerInfo(); - final DestinationStatistics destinationStatistics = new DestinationStatistics(); - consumerInfo.setExclusive(true); - final Queue queue = new Queue(brokerService, destination, queueMessageStore, destinationStatistics, brokerService.getTaskRunnerFactory()); - - // a workaround for this issue - // queue.setUseCache(false); - queue.systemUsage.getMemoryUsage().setLimit(1024 * 1024 * 10); - queue.setMaxAuditDepth(auditDepth); - queue.initialize(); - queue.start(); - - ProducerBrokerExchange producerExchange = new ProducerBrokerExchange(); - ProducerInfo producerInfo = new ProducerInfo(); - ProducerState producerState = new ProducerState(producerInfo); - producerExchange.setProducerState(producerState); - producerExchange.setConnectionContext(contextNotInTx); - - final CountDownLatch receivedLatch = new CountDownLatch(count); - final AtomicLong ackedCount = new AtomicLong(0); - final AtomicLong enqueueCounter = new AtomicLong(0); - final Vector errors = new Vector<>(); - - // populate the queue store, exceed memory limit so that cache is disabled - for (int i = 0; i < count; i++) { - Message message = getMessage(i); - queue.send(producerExchange, message); - } - - assertEquals("store count is correct", count, queueMessageStore.getMessageCount()); - - // pull from store in small windows - Subscription subscription = new Subscription() { - - private SubscriptionStatistics subscriptionStatistics = new SubscriptionStatistics(); - - @Override - public long getPendingMessageSize() { - return 0; - } - - @Override - public void add(MessageReference node) throws Exception { - if (enqueueCounter.get() != node.getMessageId().getProducerSequenceId()) { - errors.add("Not in sequence at: " + enqueueCounter.get() + ", received: " + node.getMessageId().getProducerSequenceId()); - } - assertEquals("is in order", enqueueCounter.get(), node.getMessageId().getProducerSequenceId()); - receivedLatch.countDown(); - enqueueCounter.incrementAndGet(); - node.decrementReferenceCount(); - } - - @Override - public void add(ConnectionContext context, Destination destination) throws Exception { - } - - @Override - public int countBeforeFull() { - if (isFull()) { - return 0; - } else { - return fullWindow - (int) (enqueueCounter.get() - ackedCount.get()); - } - } - - @Override - public void destroy() { - } - - @Override - public void gc() { - } - - @Override - public ConsumerInfo getConsumerInfo() { - return consumerInfo; - } - - @Override - public ConnectionContext getContext() { - return null; - } - - @Override - public long getDequeueCounter() { - return 0; - } - - @Override - public long getDispatchedCounter() { - return 0; - } - - @Override - public int getDispatchedQueueSize() { - return 0; - } - - @Override - public long getEnqueueCounter() { - return 0; - } - - @Override - public int getInFlightSize() { - return 0; - } - - @Override - public int getInFlightUsage() { - return 0; - } - - @Override - public ObjectName getObjectName() { - return null; - } - - @Override - public int getPendingQueueSize() { - return 0; - } - - @Override - public int getPrefetchSize() { - return 0; - } - - @Override - public String getSelector() { - return null; - } - - @Override - public boolean isBrowser() { - return false; - } - - @Override - public boolean isFull() { - return (enqueueCounter.get() - ackedCount.get()) >= fullWindow; - } - - @Override - public boolean isHighWaterMark() { - return false; - } - - @Override - public boolean isLowWaterMark() { - return false; - } - - @Override - public boolean isRecoveryRequired() { - return false; - } - - @Override - public boolean matches(MessageReference node, MessageEvaluationContext context) throws IOException { - return true; - } - - @Override - public boolean matches(ActiveMQDestination destination) { - return true; - } - - @Override - public void processMessageDispatchNotification(MessageDispatchNotification mdn) throws Exception { - } - - @Override - public Response pullMessage(ConnectionContext context, MessagePull pull) throws Exception { - return null; - } - - @Override - public boolean isWildcard() { - return false; - } - - @Override - public List remove(ConnectionContext context, Destination destination) throws Exception { - return null; - } - - @Override - public void setObjectName(ObjectName objectName) { - } - - @Override - public void setSelector(String selector) throws InvalidSelectorException, UnsupportedOperationException { - } - - @Override - public void updateConsumerPrefetch(int newPrefetch) { - } - - @Override - public boolean addRecoveredMessage(ConnectionContext context, MessageReference message) throws Exception { - return false; - } - - @Override - public ActiveMQDestination getActiveMQDestination() { - return destination; - } - - @Override - public void acknowledge(ConnectionContext context, MessageAck ack) throws Exception { - } - - @Override - public int getCursorMemoryHighWaterMark() { - return 0; - } - - @Override - public void setCursorMemoryHighWaterMark(int cursorMemoryHighWaterMark) { - } - - @Override - public boolean isSlowConsumer() { - return false; - } - - @Override - public void unmatched(MessageReference node) throws IOException { - } - - @Override - public long getTimeOfLastMessageAck() { - return 0; - } - - @Override - public long getConsumedCount() { - return 0; - } - - @Override - public void incrementConsumedCount() { - - } - - @Override - public void resetConsumedCount() { - - } - - @Override - public SubscriptionStatistics getSubscriptionStatistics() { - return subscriptionStatistics; - } - - @Override - public long getInFlightMessageSize() { - return subscriptionStatistics.getInflightMessageSize().getTotalSize(); - } - }; - - queue.addSubscription(contextNotInTx, subscription); - int removeIndex = 0; - do { - // Simulate periodic acks in small but recent windows - long receivedCount = enqueueCounter.get(); - if (receivedCount > ackStartIndex) { - if (receivedCount >= removeIndex + ackWindow) { - for (int j = 0; j < ackBatchSize; j++, removeIndex++) { - ackedCount.incrementAndGet(); - MessageAck ack = new MessageAck(); - ack.setLastMessageId(new MessageId(mesageIdRoot + removeIndex)); - ack.setMessageCount(1); - queue.removeMessage(contextNotInTx, subscription, new IndirectMessageReference(getMessage(removeIndex)), ack); - queue.wakeup(); - - } - if (removeIndex % 1000 == 0) { - LOG.info("acked: " + removeIndex); - persistenceAdapter.checkpoint(true); - } - } - } - - } while (!receivedLatch.await(0, TimeUnit.MILLISECONDS) && errors.isEmpty()); - - assertTrue("There are no errors: " + errors, errors.isEmpty()); - assertEquals(count, enqueueCounter.get()); - assertEquals("store count is correct", count - removeIndex, queueMessageStore.getMessageCount()); - } - - private Message getMessage(int i) throws Exception { - ActiveMQTextMessage message = new ActiveMQTextMessage(); - message.setMessageId(new MessageId(mesageIdRoot + i)); - message.setDestination(destination); - message.setPersistent(true); - message.setResponseRequired(true); - message.setText("Msg:" + i + " " + text); - assertEquals(message.getMessageId().getProducerSequenceId(), i); - return message; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueOptimizedDispatchExceptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueOptimizedDispatchExceptionTest.java deleted file mode 100644 index 333ee95571..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueOptimizedDispatchExceptionTest.java +++ /dev/null @@ -1,253 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.region; - -import java.io.IOException; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.Connection; -import org.apache.activemq.broker.ConnectionContext; -import org.apache.activemq.broker.Connector; -import org.apache.activemq.broker.ProducerBrokerExchange; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTextMessage; -import org.apache.activemq.command.Command; -import org.apache.activemq.command.ConnectionControl; -import org.apache.activemq.command.Message; -import org.apache.activemq.command.MessageId; -import org.apache.activemq.command.ProducerInfo; -import org.apache.activemq.command.Response; -import org.apache.activemq.state.ProducerState; -import org.apache.activemq.store.MessageStore; -import org.apache.activemq.store.PersistenceAdapter; -import org.apache.activemq.usage.MemoryUsage; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -public class QueueOptimizedDispatchExceptionTest { - - private static final Logger LOG = LoggerFactory.getLogger(QueueOptimizedDispatchExceptionTest.class); - - private static final String brokerName = "testBroker"; - private static final String brokerUrl = "vm://" + brokerName; - private static final int count = 50; - - private final static String mesageIdRoot = "11111:22222:"; - private final ActiveMQQueue destination = new ActiveMQQueue("queue-" + QueueOptimizedDispatchExceptionTest.class.getSimpleName()); - private final int messageBytesSize = 256; - private final String text = new String(new byte[messageBytesSize]); - - private BrokerService broker; - - @Before - public void setUp() throws Exception { - - // Setup and start the broker - broker = new BrokerService(); - broker.setBrokerName(brokerName); - broker.setPersistent(false); - broker.setSchedulerSupport(false); - broker.setUseJmx(false); - broker.setUseShutdownHook(false); - broker.addConnector(brokerUrl); - - // Start the broker - broker.start(); - broker.waitUntilStarted(); - } - - @After - public void tearDown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } - - private class MockMemoryUsage extends MemoryUsage { - - private boolean full = true; - - public void setFull(boolean full) { - this.full = full; - } - - @Override - public boolean isFull() { - return full; - } - } - - @Test - public void TestOptimizedDispatchCME() throws Exception { - final PersistenceAdapter persistenceAdapter = broker.getPersistenceAdapter(); - final MessageStore queueMessageStore = persistenceAdapter.createQueueMessageStore(destination); - final ConnectionContext contextNotInTx = new ConnectionContext(); - contextNotInTx.setConnection(new Connection() { - - @Override - public void stop() throws Exception { - } - - @Override - public void start() throws Exception { - } - - @Override - public void updateClient(ConnectionControl control) { - } - - @Override - public void serviceExceptionAsync(IOException e) { - } - - @Override - public void serviceException(Throwable error) { - } - - @Override - public Response service(Command command) { - return null; - } - - @Override - public boolean isSlow() { - return false; - } - - @Override - public boolean isNetworkConnection() { - return false; - } - - @Override - public boolean isManageable() { - return false; - } - - @Override - public boolean isFaultTolerantConnection() { - return false; - } - - @Override - public boolean isConnected() { - return true; - } - - @Override - public boolean isBlocked() { - return false; - } - - @Override - public boolean isActive() { - return false; - } - - @Override - public ConnectionStatistics getStatistics() { - return null; - } - - @Override - public String getRemoteAddress() { - return null; - } - - @Override - public int getDispatchQueueSize() { - return 0; - } - - @Override - public Connector getConnector() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getConnectionId() { - return null; - } - - @Override - public void dispatchSync(Command message) { - } - - @Override - public void dispatchAsync(Command command) { - } - - @Override - public int getActiveTransactionCount() { - return 0; - } - - @Override - public Long getOldestActiveTransactionDuration() { - return null; - } - }); - - final DestinationStatistics destinationStatistics = new DestinationStatistics(); - final Queue queue = new Queue(broker, destination, queueMessageStore, destinationStatistics, broker.getTaskRunnerFactory()); - - final MockMemoryUsage usage = new MockMemoryUsage(); - - queue.setOptimizedDispatch(true); - queue.initialize(); - queue.start(); - queue.memoryUsage = usage; - - ProducerBrokerExchange producerExchange = new ProducerBrokerExchange(); - ProducerInfo producerInfo = new ProducerInfo(); - ProducerState producerState = new ProducerState(producerInfo); - producerExchange.setProducerState(producerState); - producerExchange.setConnectionContext(contextNotInTx); - - // populate the queue store, exceed memory limit so that cache is disabled - for (int i = 0; i < count; i++) { - Message message = getMessage(i); - queue.send(producerExchange, message); - } - - usage.setFull(false); - - try { - queue.wakeup(); - } catch (Exception e) { - LOG.error("Queue threw an unexpected exception: " + e.toString()); - fail("Should not throw an exception."); - } - } - - private Message getMessage(int i) throws Exception { - ActiveMQTextMessage message = new ActiveMQTextMessage(); - message.setMessageId(new MessageId(mesageIdRoot + i)); - message.setDestination(destination); - message.setPersistent(false); - message.setResponseRequired(true); - message.setText("Msg:" + i + " " + text); - assertEquals(message.getMessageId().getProducerSequenceId(), i); - return message; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueuePurgeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueuePurgeTest.java deleted file mode 100644 index 799ae715b1..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueuePurgeTest.java +++ /dev/null @@ -1,209 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.region; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; -import java.io.File; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.CombinationTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.jmx.QueueViewMBean; -import org.apache.activemq.broker.region.policy.FilePendingQueueMessageStoragePolicy; -import org.apache.activemq.broker.region.policy.PendingQueueMessageStoragePolicy; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.util.DefaultTestAppender; -import org.apache.log4j.Appender; -import org.apache.log4j.Level; -import org.apache.log4j.spi.LoggingEvent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class QueuePurgeTest extends CombinationTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(QueuePurgeTest.class); - private static final int NUM_TO_SEND = 20000; - private final String MESSAGE_TEXT = new String(new byte[1024]); - BrokerService broker; - ConnectionFactory factory; - Connection connection; - Session session; - Queue queue; - MessageConsumer consumer; - - @Override - protected void setUp() throws Exception { - setMaxTestTime(10 * 60 * 1000); // 10 mins - setAutoFail(true); - super.setUp(); - broker = new BrokerService(); - - File testDataDir = new File("target/activemq-data/QueuePurgeTest"); - broker.setDataDirectoryFile(testDataDir); - broker.setUseJmx(true); - broker.setDeleteAllMessagesOnStartup(true); - broker.getSystemUsage().getMemoryUsage().setLimit(1024L * 1024 * 64); - KahaDBPersistenceAdapter persistenceAdapter = new KahaDBPersistenceAdapter(); - persistenceAdapter.setDirectory(new File(testDataDir, "kahadb")); - broker.setPersistenceAdapter(persistenceAdapter); - broker.addConnector("tcp://localhost:0"); - broker.start(); - factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri().toString()); - connection = factory.createConnection(); - connection.start(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - if (consumer != null) { - consumer.close(); - } - session.close(); - connection.stop(); - connection.close(); - broker.stop(); - } - - public void testPurgeLargeQueue() throws Exception { - applyBrokerSpoolingPolicy(); - createProducerAndSendMessages(NUM_TO_SEND); - QueueViewMBean proxy = getProxyToQueueViewMBean(); - LOG.info("purging.."); - - org.apache.log4j.Logger log4jLogger = org.apache.log4j.Logger.getLogger(org.apache.activemq.broker.region.Queue.class); - final AtomicBoolean gotPurgeLogMessage = new AtomicBoolean(false); - - Appender appender = new DefaultTestAppender() { - @Override - public void doAppend(LoggingEvent event) { - if (event.getMessage() instanceof String) { - String message = (String) event.getMessage(); - if (message.contains("purged of " + NUM_TO_SEND + " messages")) { - LOG.info("Received a log message: {} ", event.getMessage()); - gotPurgeLogMessage.set(true); - } - } - } - }; - - Level level = log4jLogger.getLevel(); - log4jLogger.setLevel(Level.INFO); - log4jLogger.addAppender(appender); - try { - - proxy.purge(); - - } finally { - log4jLogger.setLevel(level); - log4jLogger.removeAppender(appender); - } - - assertEquals("Queue size is not zero, it's " + proxy.getQueueSize(), 0, proxy.getQueueSize()); - assertTrue("cache is disabled, temp store being used", !proxy.isCacheEnabled()); - assertTrue("got expected info purge log message", gotPurgeLogMessage.get()); - } - - public void testRepeatedExpiryProcessingOfLargeQueue() throws Exception { - applyBrokerSpoolingPolicy(); - final int expiryPeriod = 500; - applyExpiryDuration(expiryPeriod); - createProducerAndSendMessages(NUM_TO_SEND); - QueueViewMBean proxy = getProxyToQueueViewMBean(); - LOG.info("waiting for expiry to kick in a bunch of times to verify it does not blow mem"); - Thread.sleep(5000); - assertEquals("Queue size is has not changed " + proxy.getQueueSize(), NUM_TO_SEND, proxy.getQueueSize()); - } - - private void applyExpiryDuration(int i) { - broker.getDestinationPolicy().getDefaultEntry().setExpireMessagesPeriod(i); - } - - private void applyBrokerSpoolingPolicy() { - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setProducerFlowControl(false); - PendingQueueMessageStoragePolicy pendingQueuePolicy = new FilePendingQueueMessageStoragePolicy(); - defaultEntry.setPendingQueuePolicy(pendingQueuePolicy); - policyMap.setDefaultEntry(defaultEntry); - broker.setDestinationPolicy(policyMap); - } - - public void testPurgeLargeQueueWithConsumer() throws Exception { - applyBrokerSpoolingPolicy(); - createProducerAndSendMessages(NUM_TO_SEND); - QueueViewMBean proxy = getProxyToQueueViewMBean(); - createConsumer(); - long start = System.currentTimeMillis(); - LOG.info("purging.."); - proxy.purge(); - LOG.info("purge done: " + (System.currentTimeMillis() - start) + "ms"); - assertEquals("Queue size is not zero, it's " + proxy.getQueueSize(), 0, proxy.getQueueSize()); - assertEquals("usage goes to duck", 0, proxy.getMemoryPercentUsage()); - Message msg; - do { - msg = consumer.receive(1000); - if (msg != null) { - msg.acknowledge(); - } - } while (msg != null); - assertEquals("Queue size not valid", 0, proxy.getQueueSize()); - } - - private QueueViewMBean getProxyToQueueViewMBean() throws MalformedObjectNameException, JMSException { - ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + queue.getQueueName()); - QueueViewMBean proxy = (QueueViewMBean) broker.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); - return proxy; - } - - private void createProducerAndSendMessages(int numToSend) throws Exception { - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - queue = session.createQueue("test1"); - MessageProducer producer = session.createProducer(queue); - for (int i = 0; i < numToSend; i++) { - TextMessage message = session.createTextMessage(MESSAGE_TEXT + i); - if (i != 0 && i % 10000 == 0) { - LOG.info("sent: " + i); - } - producer.send(message); - } - producer.close(); - } - - private void createConsumer() throws Exception { - consumer = session.createConsumer(queue); - // wait for buffer fill out - Thread.sleep(5 * 1000); - for (int i = 0; i < 500; ++i) { - Message message = consumer.receive(); - message.acknowledge(); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueResendDuringShutdownTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueResendDuringShutdownTest.java deleted file mode 100644 index dd2c4140e5..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/QueueResendDuringShutdownTest.java +++ /dev/null @@ -1,249 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.region; - -import javax.jms.Connection; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQQueue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; - -/** - * Confirm that the broker does not resend unacknowledged messages during a broker shutdown. - */ -public class QueueResendDuringShutdownTest { - - private static final Logger LOG = LoggerFactory.getLogger(QueueResendDuringShutdownTest.class); - public static final int NUM_CONNECTION_TO_TEST = 8; - - private static boolean iterationFoundFailure = false; - - private BrokerService broker; - private ActiveMQConnectionFactory factory; - private Connection[] connections; - private Connection producerConnection; - private Queue queue; - - private final Object messageReceiveSync = new Object(); - private int receiveCount; - - @Before - public void setUp() throws Exception { - this.receiveCount = 0; - - this.broker = new BrokerService(); - this.broker.setPersistent(false); - this.broker.start(); - this.broker.waitUntilStarted(); - - this.factory = new ActiveMQConnectionFactory(broker.getVmConnectorURI()); - this.queue = new ActiveMQQueue("TESTQUEUE"); - - connections = new Connection[NUM_CONNECTION_TO_TEST]; - int iter = 0; - while (iter < NUM_CONNECTION_TO_TEST) { - this.connections[iter] = factory.createConnection(); - iter++; - } - - this.producerConnection = factory.createConnection(); - this.producerConnection.start(); - } - - @After - public void cleanup() throws Exception { - for (Connection oneConnection : connections) { - if (oneConnection != null) { - closeConnection(oneConnection); - } - } - connections = null; - - if (this.producerConnection != null) { - closeConnection(this.producerConnection); - this.producerConnection = null; - } - - this.broker.stop(); - this.broker.waitUntilStopped(); - } - - @Test(timeout = 3000) - public void testRedeliverAtBrokerShutdownAutoAckMsgListenerIter1() throws Throwable { - runTestIteration(); - } - - @Test(timeout = 3000) - public void testRedeliverAtBrokerShutdownAutoAckMsgListenerIter2() throws Throwable { - runTestIteration(); - } - - @Test(timeout = 3000) - public void testRedeliverAtBrokerShutdownAutoAckMsgListenerIter3() throws Throwable { - runTestIteration(); - } - - /** - * Run one iteration of the test, skipping it if a failure was found on a prior iteration since a single failure is - * enough. Also keep track of the state of failure for the iteration. - */ - protected void runTestIteration() throws Throwable { - if (iterationFoundFailure) { - LOG.info("skipping test iteration; failure previously detected"); - return; - } - try { - testRedeliverAtBrokerShutdownAutoAckMsgListener(); - } catch (Throwable thrown) { - iterationFoundFailure = true; - throw thrown; - } - } - - protected void testRedeliverAtBrokerShutdownAutoAckMsgListener() throws Exception { - // Start consumers on all of the connections - for (Connection oneConnection : connections) { - MessageConsumer consumer = startupConsumer(oneConnection, false, Session.AUTO_ACKNOWLEDGE); - configureMessageListener(consumer); - oneConnection.start(); - } - - // Send one message to the Queue and wait a short time for the dispatch to occur. - this.sendMessage(); - waitForMessage(1000); - - // Verify one consumer received it - assertEquals(1, this.receiveCount); - - // Shutdown the broker - this.broker.stop(); - this.broker.waitUntilStopped(); - delay(100, "give queue time flush"); - - // Verify still only one consumer received it - assertEquals(1, this.receiveCount); - } - - /** - * Start a consumer on the given connection using the session transaction and acknowledge settings given. - */ - protected MessageConsumer startupConsumer(Connection conn, boolean transInd, int ackMode) throws JMSException { - Session sess; - MessageConsumer consumer; - - sess = conn.createSession(transInd, ackMode); - consumer = sess.createConsumer(queue); - - return consumer; - } - - /** - * Mark the receipt of a message from one of the consumers. - */ - protected void messageReceived() { - synchronized (this) { - this.receiveCount++; - synchronized (this.messageReceiveSync) { - this.messageReceiveSync.notifyAll(); - } - } - } - - /** - * Setup the MessageListener for the given consumer. The listener uses a long delay on receiving the message to - * simulate the reported case of problems at shutdown caused by a message listener's connection closing while it is - * still processing. - */ - protected void configureMessageListener(MessageConsumer consumer) throws JMSException { - final MessageConsumer fConsumer = consumer; - - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message msg) { - LOG.debug("got a message on consumer {}", fConsumer); - messageReceived(); - - // Delay long enough for the consumer to get closed while this delay is active. - delay(3000, "pause so connection shutdown leads to unacked message redelivery"); - } - }); - } - - /** - * Send a test message now. - */ - protected void sendMessage() throws JMSException { - Session sess = this.producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer prod = sess.createProducer(queue); - prod.send(sess.createTextMessage("X-TEST-MSG-X")); - prod.close(); - sess.close(); - } - - /** - * Close the given connection safely and log any exception caught. - */ - protected void closeConnection(Connection conn) { - try { - conn.close(); - } catch (JMSException jmsExc) { - LOG.info("failed to cleanup connection", jmsExc); - } - } - - /** - * Pause for the given length of time, in milliseconds, logging an interruption if one occurs. Don't try to - * recover from interrupt - the test case does not support interrupting and such an occurrence likely means the - * test is being aborted. - */ - protected void delay(long delayMs, String desc) { - try { - Thread.sleep(delayMs); - } catch (InterruptedException intExc) { - LOG.warn("sleep interrupted: " + desc, intExc); - } - } - - /** - * Wait up to the specified duration for a message to be received by any consumer. - */ - protected void waitForMessage(long delayMs) { - try { - synchronized (this.messageReceiveSync) { - while (this.receiveCount == 0) { - this.messageReceiveSync.wait(delayMs); - } - } - } catch (InterruptedException intExc) { - LOG.warn("sleep interrupted: wait for message to arrive"); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/SubscriptionAddRemoveQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/SubscriptionAddRemoveQueueTest.java deleted file mode 100644 index d0ed8ef9c1..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/SubscriptionAddRemoveQueueTest.java +++ /dev/null @@ -1,433 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.region; - -import javax.jms.InvalidSelectorException; -import javax.management.ObjectName; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.atomic.AtomicInteger; - -import junit.framework.TestCase; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.ConnectionContext; -import org.apache.activemq.broker.ProducerBrokerExchange; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQMessage; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ConsumerInfo; -import org.apache.activemq.command.Message; -import org.apache.activemq.command.MessageAck; -import org.apache.activemq.command.MessageDispatchNotification; -import org.apache.activemq.command.MessageId; -import org.apache.activemq.command.MessagePull; -import org.apache.activemq.command.ProducerInfo; -import org.apache.activemq.command.Response; -import org.apache.activemq.filter.MessageEvaluationContext; -import org.apache.activemq.state.ProducerState; -import org.apache.activemq.store.MessageStore; -import org.apache.activemq.thread.TaskRunnerFactory; - -public class SubscriptionAddRemoveQueueTest extends TestCase { - - Queue queue; - - ConsumerInfo info = new ConsumerInfo(); - List subs = new ArrayList<>(); - ConnectionContext context = new ConnectionContext(); - ProducerBrokerExchange producerBrokerExchange = new ProducerBrokerExchange(); - ProducerInfo producerInfo = new ProducerInfo(); - ProducerState producerState = new ProducerState(producerInfo); - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - int numSubscriptions = 1000; - boolean working = true; - int senders = 20; - - @Override - public void setUp() throws Exception { - BrokerService brokerService = new BrokerService(); - brokerService.start(); - DestinationStatistics parentStats = new DestinationStatistics(); - parentStats.setEnabled(true); - - TaskRunnerFactory taskFactory = new TaskRunnerFactory(); - MessageStore store = null; - - info.setDestination(destination); - info.setPrefetchSize(100); - - producerBrokerExchange.setProducerState(producerState); - producerBrokerExchange.setConnectionContext(context); - - queue = new Queue(brokerService, destination, store, parentStats, taskFactory); - queue.initialize(); - } - - public void testNoDispatchToRemovedConsumers() throws Exception { - final AtomicInteger producerId = new AtomicInteger(); - Runnable sender = new Runnable() { - @Override - public void run() { - AtomicInteger id = new AtomicInteger(); - int producerIdAndIncrement = producerId.getAndIncrement(); - while (working) { - try { - Message msg = new ActiveMQMessage(); - msg.setDestination(destination); - msg.setMessageId(new MessageId(producerIdAndIncrement + ":0:" + id.getAndIncrement())); - queue.send(producerBrokerExchange, msg); - } catch (Exception e) { - e.printStackTrace(); - fail("unexpected exception in sendMessage, ex:" + e); - } - } - } - }; - - Runnable subRemover = new Runnable() { - @Override - public void run() { - for (Subscription sub : subs) { - try { - queue.removeSubscription(context, sub, 0); - } catch (Exception e) { - e.printStackTrace(); - fail("unexpected exception in removeSubscription, ex:" + e); - } - } - } - }; - - for (int i = 0; i < numSubscriptions; i++) { - SimpleImmediateDispatchSubscription sub = new SimpleImmediateDispatchSubscription(); - subs.add(sub); - queue.addSubscription(context, sub); - } - assertEquals("there are X subscriptions", numSubscriptions, queue.getDestinationStatistics().getConsumers().getCount()); - ExecutorService executor = Executors.newCachedThreadPool(); - for (int i = 0; i < senders; i++) { - executor.submit(sender); - } - - Thread.sleep(1000); - for (SimpleImmediateDispatchSubscription sub : subs) { - assertTrue("There are some locked messages in the subscription", hasSomeLocks(sub.dispatched)); - } - - Future result = executor.submit(subRemover); - result.get(); - working = false; - assertEquals("there are no subscriptions", 0, queue.getDestinationStatistics().getConsumers().getCount()); - - for (SimpleImmediateDispatchSubscription sub : subs) { - assertTrue("There are no locked messages in any removed subscriptions", !hasSomeLocks(sub.dispatched)); - } - - } - - private boolean hasSomeLocks(List dispatched) { - boolean hasLock = false; - for (MessageReference mr : dispatched) { - QueueMessageReference qmr = (QueueMessageReference) mr; - if (qmr.getLockOwner() != null) { - hasLock = true; - break; - } - } - return hasLock; - } - - public class SimpleImmediateDispatchSubscription implements Subscription, LockOwner { - - private SubscriptionStatistics subscriptionStatistics = new SubscriptionStatistics(); - List dispatched = Collections.synchronizedList(new ArrayList()); - - @Override - public long getPendingMessageSize() { - return 0; - } - - @Override - public void acknowledge(ConnectionContext context, MessageAck ack) throws Exception { - } - - @Override - public void add(MessageReference node) throws Exception { - // immediate dispatch - QueueMessageReference qmr = (QueueMessageReference) node; - qmr.lock(this); - dispatched.add(qmr); - } - - @Override - public ConnectionContext getContext() { - return null; - } - - @Override - public int getCursorMemoryHighWaterMark() { - return 0; - } - - @Override - public void setCursorMemoryHighWaterMark(int cursorMemoryHighWaterMark) { - } - - @Override - public boolean isSlowConsumer() { - return false; - } - - @Override - public void unmatched(MessageReference node) throws IOException { - } - - @Override - public long getTimeOfLastMessageAck() { - return 0; - } - - @Override - public long getConsumedCount() { - return 0; - } - - @Override - public void incrementConsumedCount() { - } - - @Override - public void resetConsumedCount() { - } - - @Override - public void add(ConnectionContext context, Destination destination) throws Exception { - } - - @Override - public void destroy() { - } - - @Override - public void gc() { - } - - @Override - public ConsumerInfo getConsumerInfo() { - return info; - } - - @Override - public long getDequeueCounter() { - return 0; - } - - @Override - public long getDispatchedCounter() { - return 0; - } - - @Override - public int getDispatchedQueueSize() { - return 0; - } - - @Override - public long getEnqueueCounter() { - return 0; - } - - @Override - public int getInFlightSize() { - return 0; - } - - @Override - public int getInFlightUsage() { - return 0; - } - - @Override - public ObjectName getObjectName() { - return null; - } - - @Override - public int getPendingQueueSize() { - return 0; - } - - @Override - public int getPrefetchSize() { - return 0; - } - - @Override - public String getSelector() { - return null; - } - - @Override - public boolean isBrowser() { - return false; - } - - @Override - public boolean isFull() { - return false; - } - - @Override - public boolean isHighWaterMark() { - return false; - } - - @Override - public boolean isLowWaterMark() { - return false; - } - - @Override - public boolean isRecoveryRequired() { - return false; - } - - public boolean isSlave() { - return false; - } - - @Override - public boolean matches(MessageReference node, MessageEvaluationContext context) throws IOException { - return true; - } - - @Override - public boolean matches(ActiveMQDestination destination) { - return false; - } - - @Override - public void processMessageDispatchNotification(MessageDispatchNotification mdn) throws Exception { - } - - @Override - public Response pullMessage(ConnectionContext context, MessagePull pull) throws Exception { - return null; - } - - @Override - public boolean isWildcard() { - return false; - } - - @Override - public List remove(ConnectionContext context, Destination destination) throws Exception { - return new ArrayList<>(dispatched); - } - - @Override - public void setObjectName(ObjectName objectName) { - } - - @Override - public void setSelector(String selector) throws InvalidSelectorException, UnsupportedOperationException { - } - - @Override - public void updateConsumerPrefetch(int newPrefetch) { - } - - @Override - public boolean addRecoveredMessage(ConnectionContext context, MessageReference message) throws Exception { - return false; - } - - @Override - public ActiveMQDestination getActiveMQDestination() { - return null; - } - - @Override - public int getLockPriority() { - return 0; - } - - @Override - public boolean isLockExclusive() { - return false; - } - - public void addDestination(Destination destination) { - } - - public void removeDestination(Destination destination) { - } - - @Override - public int countBeforeFull() { - return 10; - } - - @Override - public SubscriptionStatistics getSubscriptionStatistics() { - return subscriptionStatistics; - } - - @Override - public long getInFlightMessageSize() { - return subscriptionStatistics.getInflightMessageSize().getTotalSize(); - } - - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/UniquePropertyMessageEvictionStrategyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/UniquePropertyMessageEvictionStrategyTest.java deleted file mode 100644 index 8ac46231c8..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/UniquePropertyMessageEvictionStrategyTest.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.broker.region; - -import javax.jms.Connection; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.util.ArrayList; -import java.util.List; - -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.ConstantPendingMessageLimitStrategy; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.broker.region.policy.UniquePropertyMessageEvictionStrategy; - -public class UniquePropertyMessageEvictionStrategyTest extends EmbeddedBrokerTestSupport { - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - final List policyEntries = new ArrayList<>(); - final PolicyEntry entry = new PolicyEntry(); - entry.setTopic(">"); - - entry.setAdvisoryForDiscardingMessages(true); - entry.setTopicPrefetch(1); - - ConstantPendingMessageLimitStrategy pendingMessageLimitStrategy = new ConstantPendingMessageLimitStrategy(); - pendingMessageLimitStrategy.setLimit(10); - entry.setPendingMessageLimitStrategy(pendingMessageLimitStrategy); - - UniquePropertyMessageEvictionStrategy messageEvictionStrategy = new UniquePropertyMessageEvictionStrategy(); - messageEvictionStrategy.setPropertyName("sequenceI"); - entry.setMessageEvictionStrategy(messageEvictionStrategy); - - // let evicted messages disappear - entry.setDeadLetterStrategy(null); - policyEntries.add(entry); - - final PolicyMap policyMap = new PolicyMap(); - policyMap.setPolicyEntries(policyEntries); - broker.setDestinationPolicy(policyMap); - - return broker; - } - - public void testEviction() throws Exception { - Connection conn = connectionFactory.createConnection(); - conn.start(); - Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - javax.jms.Topic destination = session.createTopic("TEST"); - - MessageProducer producer = session.createProducer(destination); - MessageConsumer consumer = session.createConsumer(destination); - - for (int i = 0; i < 10; i++) { - for (int j = 0; j < 10; j++) { - TextMessage msg = session.createTextMessage("message " + i + j); - msg.setIntProperty("sequenceI", i); - msg.setIntProperty("sequenceJ", j); - producer.send(msg); - Thread.sleep(100); - } - } - - for (int i = 0; i < 11; i++) { - javax.jms.Message msg = consumer.receive(1000); - assertNotNull(msg); - int seqI = msg.getIntProperty("sequenceI"); - int seqJ = msg.getIntProperty("sequenceJ"); - if (i == 0) { - assertEquals(0, seqI); - assertEquals(0, seqJ); - } else { - assertEquals(9, seqJ); - assertEquals(i - 1, seqI); - } - //System.out.println(msg.getIntProperty("sequenceI") + " " + msg.getIntProperty("sequenceJ")); - } - - javax.jms.Message msg = consumer.receive(1000); - assertNull(msg); - - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorDurableTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorDurableTest.java deleted file mode 100644 index 30296899a9..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorDurableTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.region.cursors; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageConsumer; -import javax.jms.Session; -import javax.jms.Topic; - -import org.apache.activemq.broker.BrokerService; - -/** - * - */ -public class CursorDurableTest extends CursorSupport { - - @Override - protected Destination getDestination(Session session) throws JMSException { - String topicName = getClass().getName(); - return session.createTopic(topicName); - } - - @Override - protected Connection getConsumerConnection(ConnectionFactory fac) throws JMSException { - Connection connection = fac.createConnection(); - connection.setClientID("testConsumer"); - connection.start(); - return connection; - } - - @Override - protected MessageConsumer getConsumer(Connection connection) throws Exception { - Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = (Topic) getDestination(consumerSession); - MessageConsumer consumer = consumerSession.createDurableSubscriber(topic, "testConsumer"); - return consumer; - } - - @Override - protected void configureBroker(BrokerService answer) throws Exception { - answer.setDeleteAllMessagesOnStartup(true); - answer.addConnector(bindAddress); - answer.setDeleteAllMessagesOnStartup(true); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorQueueStoreTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorQueueStoreTest.java deleted file mode 100644 index 5a0123136e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorQueueStoreTest.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.activemq.broker.region.cursors; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageConsumer; -import javax.jms.Session; - -import junit.framework.Test; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.broker.region.policy.StorePendingQueueMessageStoragePolicy; - -/** - * - */ -public class CursorQueueStoreTest extends CursorSupport { - - @Override - protected Destination getDestination(Session session) throws JMSException { - String queueName = "QUEUE" + getClass().getName(); - return session.createQueue(queueName); - } - - @Override - protected Connection getConsumerConnection(ConnectionFactory fac) throws JMSException { - Connection connection = fac.createConnection(); - connection.setClientID("testConsumer"); - connection.start(); - return connection; - } - - @Override - protected MessageConsumer getConsumer(Connection connection) throws Exception { - Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination dest = getDestination(consumerSession); - MessageConsumer consumer = consumerSession.createConsumer(dest); - return consumer; - } - - @Override - protected void configureBroker(BrokerService answer) throws Exception { - PolicyEntry policy = new PolicyEntry(); - policy.setPendingQueuePolicy(new StorePendingQueueMessageStoragePolicy()); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - answer.setDestinationPolicy(pMap); - answer.setDeleteAllMessagesOnStartup(true); - answer.addConnector(bindAddress); - answer.setDeleteAllMessagesOnStartup(true); - } - - public static Test suite() { - return suite(CursorQueueStoreTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorSupport.java deleted file mode 100644 index 43cfb00cc7..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/CursorSupport.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.activemq.broker.region.cursors; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.CombinationTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public abstract class CursorSupport extends CombinationTestSupport { - - public int MESSAGE_COUNT = 500; - public int PREFETCH_SIZE = 50; - private static final Logger LOG = LoggerFactory.getLogger(CursorSupport.class); - - protected BrokerService broker; - protected String bindAddress = "tcp://localhost:60706"; - - protected abstract Destination getDestination(Session session) throws JMSException; - - protected abstract MessageConsumer getConsumer(Connection connection) throws Exception; - - protected abstract void configureBroker(BrokerService answer) throws Exception; - - public void testSendFirstThenConsume() throws Exception { - ConnectionFactory factory = createConnectionFactory(); - Connection consumerConnection = getConsumerConnection(factory); - MessageConsumer consumer = getConsumer(consumerConnection); - consumerConnection.close(); - Connection producerConnection = factory.createConnection(); - producerConnection.start(); - Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(getDestination(session)); - List senderList = new ArrayList<>(); - for (int i = 0; i < MESSAGE_COUNT; i++) { - Message msg = session.createTextMessage("test" + i); - senderList.add(msg); - producer.send(msg); - } - producerConnection.close(); - // now consume the messages - consumerConnection = getConsumerConnection(factory); - // create durable subs - consumer = getConsumer(consumerConnection); - List consumerList = new ArrayList<>(); - for (int i = 0; i < MESSAGE_COUNT; i++) { - Message msg = consumer.receive(1000 * 5); - assertNotNull("Message " + i + " was missing.", msg); - consumerList.add(msg); - } - assertEquals(senderList, consumerList); - consumerConnection.close(); - } - - public void initCombosForTestSendWhilstConsume() { - addCombinationValues("MESSAGE_COUNT", new Object[]{Integer.valueOf(400), Integer.valueOf(500)}); - addCombinationValues("PREFETCH_SIZE", new Object[]{Integer.valueOf(100), Integer.valueOf(50)}); - } - - public void testSendWhilstConsume() throws Exception { - ConnectionFactory factory = createConnectionFactory(); - Connection consumerConnection = getConsumerConnection(factory); - // create durable subs - MessageConsumer consumer = getConsumer(consumerConnection); - consumerConnection.close(); - Connection producerConnection = factory.createConnection(); - producerConnection.start(); - Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(getDestination(session)); - List senderList = new ArrayList<>(); - for (int i = 0; i < MESSAGE_COUNT / 10; i++) { - TextMessage msg = session.createTextMessage("test" + i); - senderList.add(msg); - producer.send(msg); - } - // now consume the messages - consumerConnection = getConsumerConnection(factory); - // create durable subs - consumer = getConsumer(consumerConnection); - final List consumerList = new ArrayList<>(); - final CountDownLatch latch = new CountDownLatch(1); - consumer.setMessageListener(new MessageListener() { - - @Override - public void onMessage(Message msg) { - try { - // sleep to act as a slow consumer - // which will force a mix of direct and polled dispatching - // using the cursor on the broker - Thread.sleep(50); - } catch (Exception e) { - e.printStackTrace(); - } - consumerList.add(msg); - if (consumerList.size() == MESSAGE_COUNT) { - latch.countDown(); - } - } - }); - for (int i = MESSAGE_COUNT / 10; i < MESSAGE_COUNT; i++) { - TextMessage msg = session.createTextMessage("test" + i); - senderList.add(msg); - producer.send(msg); - } - latch.await(300000, TimeUnit.MILLISECONDS); - producerConnection.close(); - consumerConnection.close(); - assertEquals("Still dipatching - count down latch not sprung", latch.getCount(), 0); - //assertEquals("cosumerList - expected: " + MESSAGE_COUNT + " but was: " + consumerList.size(), consumerList.size(), senderList.size()); - for (int i = 0; i < senderList.size(); i++) { - Message sent = senderList.get(i); - Message consumed = consumerList.get(i); - if (!sent.equals(consumed)) { - LOG.error("BAD MATCH AT POS " + i); - LOG.error(sent.toString()); - LOG.error(consumed.toString()); - /* - * log.error("\n\n\n\n\n"); for (int j = 0; j < - * consumerList.size(); j++) { log.error(consumerList.get(j)); } - */ - } - assertEquals("This should be the same at pos " + i + " in the list", sent.getJMSMessageID(), consumed.getJMSMessageID()); - } - } - - protected Connection getConsumerConnection(ConnectionFactory fac) throws JMSException { - Connection connection = fac.createConnection(); - connection.setClientID("testConsumer"); - connection.start(); - return connection; - } - - @Override - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(); - } - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - if (broker != null) { - broker.stop(); - } - } - - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(bindAddress); - Properties props = new Properties(); - props.setProperty("prefetchPolicy.durableTopicPrefetch", "" + PREFETCH_SIZE); - props.setProperty("prefetchPolicy.optimizeDurableTopicPrefetch", "" + PREFETCH_SIZE); - props.setProperty("prefetchPolicy.queuePrefetch", "" + PREFETCH_SIZE); - cf.setProperties(props); - return cf; - } - - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - configureBroker(answer); - answer.start(); - return answer; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/FilePendingMessageCursorTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/FilePendingMessageCursorTestSupport.java deleted file mode 100644 index c66f45cdbd..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/FilePendingMessageCursorTestSupport.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.activemq.broker.region.cursors; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.QueueMessageReference; -import org.apache.activemq.store.PList; -import org.apache.activemq.usage.SystemUsage; -import org.apache.activemq.util.ByteSequence; -import org.junit.After; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -public class FilePendingMessageCursorTestSupport { - - protected static final Logger LOG = LoggerFactory.getLogger(FilePendingMessageCursorTestSupport.class); - protected BrokerService brokerService; - protected FilePendingMessageCursor underTest; - - @After - public void stopBroker() throws Exception { - if (brokerService != null) { - brokerService.getTempDataStore().stop(); - } - } - - private void createBrokerWithTempStoreLimit() throws Exception { - brokerService = new BrokerService(); - brokerService.setUseJmx(false); - SystemUsage usage = brokerService.getSystemUsage(); - usage.getTempUsage().setLimit(1025 * 1024 * 15); - - // put something in the temp store to on demand initialise it - PList dud = brokerService.getTempDataStore().getPList("dud"); - dud.addFirst("A", new ByteSequence("A".getBytes())); - } - - @Test - public void testAddToEmptyCursorWhenTempStoreIsFull() throws Exception { - createBrokerWithTempStoreLimit(); - SystemUsage usage = brokerService.getSystemUsage(); - assertTrue("temp store is full: %" + usage.getTempUsage().getPercentUsage(), usage.getTempUsage().isFull()); - - underTest = new FilePendingMessageCursor(brokerService.getBroker(), "test", false); - underTest.setSystemUsage(usage); - - // ok to add - underTest.addMessageLast(QueueMessageReference.NULL_MESSAGE); - - assertFalse("cursor is not full", underTest.isFull()); - } - - @Test - public void testResetClearsIterator() throws Exception { - createBrokerWithTempStoreLimit(); - - underTest = new FilePendingMessageCursor(brokerService.getBroker(), "test", false); - // ok to add - underTest.addMessageLast(QueueMessageReference.NULL_MESSAGE); - - underTest.reset(); - underTest.release(); - - try { - underTest.hasNext(); - fail("expect npe on use of iterator after release"); - } catch (NullPointerException expected) { - } - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/OrderPendingListTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/OrderPendingListTest.java deleted file mode 100644 index 6667cf17b0..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/OrderPendingListTest.java +++ /dev/null @@ -1,454 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.region.cursors; - -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedList; - -import org.apache.activemq.broker.region.Destination; -import org.apache.activemq.broker.region.MessageReference; -import org.apache.activemq.command.ConsumerId; -import org.apache.activemq.command.Message; -import org.apache.activemq.command.MessageId; -import org.apache.activemq.util.IdGenerator; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class OrderPendingListTest { - - @Test - public void testAddMessageFirst() throws Exception { - - OrderedPendingList list = new OrderedPendingList(); - - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageFirst(new TestMessageReference(2)); - list.addMessageFirst(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageFirst(new TestMessageReference(5)); - - assertTrue(list.size() == 5); - assertEquals(5, list.getAsList().size()); - - Iterator iter = list.iterator(); - int lastId = list.size(); - while (iter.hasNext()) { - assertEquals(lastId--, iter.next().getMessageId().getProducerSequenceId()); - } - } - - @Test - public void testAddMessageLast() throws Exception { - - OrderedPendingList list = new OrderedPendingList(); - - list.addMessageLast(new TestMessageReference(1)); - list.addMessageLast(new TestMessageReference(2)); - list.addMessageLast(new TestMessageReference(3)); - list.addMessageLast(new TestMessageReference(4)); - list.addMessageLast(new TestMessageReference(5)); - - assertTrue(list.size() == 5); - assertEquals(5, list.getAsList().size()); - - Iterator iter = list.iterator(); - int lastId = 1; - while (iter.hasNext()) { - assertEquals(lastId++, iter.next().getMessageId().getProducerSequenceId()); - } - } - - @Test - public void testClear() throws Exception { - OrderedPendingList list = new OrderedPendingList(); - - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageFirst(new TestMessageReference(2)); - list.addMessageFirst(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageFirst(new TestMessageReference(5)); - - assertFalse(list.isEmpty()); - assertTrue(list.size() == 5); - assertEquals(5, list.getAsList().size()); - - list.clear(); - - assertTrue(list.isEmpty()); - assertTrue(list.size() == 0); - assertEquals(0, list.getAsList().size()); - - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageLast(new TestMessageReference(2)); - list.addMessageLast(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageLast(new TestMessageReference(5)); - - assertFalse(list.isEmpty()); - assertTrue(list.size() == 5); - assertEquals(5, list.getAsList().size()); - } - - @Test - public void testIsEmpty() throws Exception { - OrderedPendingList list = new OrderedPendingList(); - assertTrue(list.isEmpty()); - - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageFirst(new TestMessageReference(2)); - list.addMessageFirst(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageFirst(new TestMessageReference(5)); - - assertFalse(list.isEmpty()); - list.clear(); - assertTrue(list.isEmpty()); - } - - @Test - public void testSize() { - OrderedPendingList list = new OrderedPendingList(); - assertTrue(list.isEmpty()); - - assertTrue(list.size() == 0); - list.addMessageFirst(new TestMessageReference(1)); - assertTrue(list.size() == 1); - list.addMessageLast(new TestMessageReference(2)); - assertTrue(list.size() == 2); - list.addMessageFirst(new TestMessageReference(3)); - assertTrue(list.size() == 3); - list.addMessageLast(new TestMessageReference(4)); - assertTrue(list.size() == 4); - list.addMessageFirst(new TestMessageReference(5)); - assertTrue(list.size() == 5); - - assertFalse(list.isEmpty()); - list.clear(); - assertTrue(list.isEmpty()); - assertTrue(list.size() == 0); - } - - @Test - public void testRemove() throws Exception { - - OrderedPendingList list = new OrderedPendingList(); - - TestMessageReference toRemove = new TestMessageReference(6); - - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageFirst(new TestMessageReference(2)); - list.addMessageFirst(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageFirst(new TestMessageReference(5)); - - assertTrue(list.size() == 5); - assertEquals(5, list.getAsList().size()); - - list.addMessageLast(toRemove); - list.remove(toRemove); - - assertTrue(list.size() == 5); - assertEquals(5, list.getAsList().size()); - - list.remove(toRemove); - - assertTrue(list.size() == 5); - assertEquals(5, list.getAsList().size()); - - Iterator iter = list.iterator(); - int lastId = list.size(); - while (iter.hasNext()) { - assertEquals(lastId--, iter.next().getMessageId().getProducerSequenceId()); - } - - list.remove(null); - } - - @Test - public void testContains() throws Exception { - - OrderedPendingList list = new OrderedPendingList(); - - TestMessageReference toRemove = new TestMessageReference(6); - - assertFalse(list.contains(toRemove)); - assertFalse(list.contains(null)); - - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageFirst(new TestMessageReference(2)); - list.addMessageFirst(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageFirst(new TestMessageReference(5)); - - assertTrue(list.size() == 5); - assertEquals(5, list.getAsList().size()); - - list.addMessageLast(toRemove); - assertTrue(list.size() == 6); - assertTrue(list.contains(toRemove)); - list.remove(toRemove); - assertFalse(list.contains(toRemove)); - - assertTrue(list.size() == 5); - assertEquals(5, list.getAsList().size()); - } - - @Test - public void testValues() throws Exception { - - OrderedPendingList list = new OrderedPendingList(); - - TestMessageReference toRemove = new TestMessageReference(6); - - assertFalse(list.contains(toRemove)); - - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageFirst(new TestMessageReference(2)); - list.addMessageFirst(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageFirst(new TestMessageReference(5)); - - Collection values = list.values(); - assertEquals(5, values.size()); - - for (MessageReference msg : values) { - assertTrue(values.contains(msg)); - } - - assertFalse(values.contains(toRemove)); - - list.addMessageLast(toRemove); - values = list.values(); - assertEquals(6, values.size()); - for (MessageReference msg : values) { - assertTrue(values.contains(msg)); - } - - assertTrue(values.contains(toRemove)); - } - - @Test - public void testAddAll() throws Exception { - OrderedPendingList list = new OrderedPendingList(); - TestPendingList source = new TestPendingList(); - - source.addMessageFirst(new TestMessageReference(1)); - source.addMessageFirst(new TestMessageReference(2)); - source.addMessageFirst(new TestMessageReference(3)); - source.addMessageFirst(new TestMessageReference(4)); - source.addMessageFirst(new TestMessageReference(5)); - - assertTrue(list.isEmpty()); - assertEquals(5, source.size()); - list.addAll(source); - assertEquals(5, list.size()); - - for (MessageReference message : source) { - assertTrue(list.contains(message)); - } - - list.addAll(null); - } - - static class TestPendingList implements PendingList { - - private final LinkedList theList = new LinkedList<>(); - - @Override - public long messageSize() { - return 0; - } - - @Override - public boolean isEmpty() { - return theList.isEmpty(); - } - - @Override - public void clear() { - theList.clear(); - } - - @Override - public PendingNode addMessageFirst(MessageReference message) { - theList.addFirst(message); - return new PendingNode(null, message); - } - - @Override - public PendingNode addMessageLast(MessageReference message) { - theList.addLast(message); - return new PendingNode(null, message); - } - - @Override - public PendingNode remove(MessageReference message) { - if (theList.remove(message)) { - return new PendingNode(null, message); - } else { - return null; - } - } - - @Override - public int size() { - return theList.size(); - } - - @Override - public Iterator iterator() { - return theList.iterator(); - } - - @Override - public boolean contains(MessageReference message) { - return theList.contains(message); - } - - @Override - public Collection values() { - return theList; - } - - @Override - public void addAll(PendingList pendingList) { - for (MessageReference messageReference : pendingList) { - theList.add(messageReference); - } - } - - @Override - public MessageReference get(MessageId messageId) { - for (MessageReference messageReference : theList) { - if (messageReference.getMessageId().equals(messageId)) { - return messageReference; - } - } - return null; - } - } - - static class TestMessageReference implements MessageReference { - - private static final IdGenerator id = new IdGenerator(); - - private MessageId messageId; - private int referenceCount = 0; - - public TestMessageReference(int sequenceId) { - messageId = new MessageId(id.generateId() + ":1", sequenceId); - } - - @Override - public boolean canProcessAsExpired() { - return false; - } - - @Override - public MessageId getMessageId() { - return messageId; - } - - @Override - public Message getMessageHardRef() { - return null; - } - - @Override - public Message getMessage() { - return null; - } - - @Override - public boolean isPersistent() { - return false; - } - - @Override - public Destination getRegionDestination() { - return null; - } - - @Override - public int getRedeliveryCounter() { - return 0; - } - - @Override - public void incrementRedeliveryCounter() { - } - - @Override - public int getReferenceCount() { - return this.referenceCount; - } - - @Override - public int incrementReferenceCount() { - return this.referenceCount++; - } - - @Override - public int decrementReferenceCount() { - return this.referenceCount--; - } - - @Override - public ConsumerId getTargetConsumerId() { - return null; - } - - @Override - public int getSize() { - return 1; - } - - @Override - public long getExpiration() { - return 0; - } - - @Override - public String getGroupID() { - return null; - } - - @Override - public int getGroupSequence() { - return 0; - } - - @Override - public boolean isExpired() { - return false; - } - - @Override - public boolean isDropped() { - return false; - } - - @Override - public boolean isAdvisory() { - return false; - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/PrioritizedPendingListTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/PrioritizedPendingListTest.java deleted file mode 100644 index ec9b78d2a9..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/PrioritizedPendingListTest.java +++ /dev/null @@ -1,308 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.broker.region.cursors; - -import java.util.Iterator; - -import org.apache.activemq.broker.region.Destination; -import org.apache.activemq.broker.region.MessageReference; -import org.apache.activemq.command.ActiveMQMessage; -import org.apache.activemq.command.ConsumerId; -import org.apache.activemq.command.Message; -import org.apache.activemq.command.MessageId; -import org.apache.activemq.util.IdGenerator; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class PrioritizedPendingListTest { - - @Test - public void testAddMessageFirst() { - PrioritizedPendingList list = new PrioritizedPendingList(); - - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageFirst(new TestMessageReference(2)); - list.addMessageFirst(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageFirst(new TestMessageReference(5)); - - assertTrue(list.size() == 5); - - Iterator iter = list.iterator(); - int lastId = list.size(); - while (iter.hasNext()) { - assertEquals(lastId--, iter.next().getMessageId().getProducerSequenceId()); - } - } - - @Test - public void testAddMessageLast() { - - PrioritizedPendingList list = new PrioritizedPendingList(); - - list.addMessageLast(new TestMessageReference(1)); - list.addMessageLast(new TestMessageReference(2)); - list.addMessageLast(new TestMessageReference(3)); - list.addMessageLast(new TestMessageReference(4)); - list.addMessageLast(new TestMessageReference(5)); - - assertTrue(list.size() == 5); - - Iterator iter = list.iterator(); - int lastId = 1; - while (iter.hasNext()) { - assertEquals(lastId++, iter.next().getMessageId().getProducerSequenceId()); - } - } - - @Test - public void testClear() { - PrioritizedPendingList list = new PrioritizedPendingList(); - - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageFirst(new TestMessageReference(2)); - list.addMessageFirst(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageFirst(new TestMessageReference(5)); - - assertFalse(list.isEmpty()); - assertTrue(list.size() == 5); - - list.clear(); - - assertTrue(list.isEmpty()); - assertTrue(list.size() == 0); - - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageLast(new TestMessageReference(2)); - list.addMessageLast(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageLast(new TestMessageReference(5)); - - assertFalse(list.isEmpty()); - assertTrue(list.size() == 5); - } - - @Test - public void testIsEmpty() { - PrioritizedPendingList list = new PrioritizedPendingList(); - assertTrue(list.isEmpty()); - - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageFirst(new TestMessageReference(2)); - list.addMessageFirst(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageFirst(new TestMessageReference(5)); - - assertFalse(list.isEmpty()); - list.clear(); - assertTrue(list.isEmpty()); - } - - @Test - public void testRemove() { - PrioritizedPendingList list = new PrioritizedPendingList(); - - TestMessageReference toRemove = new TestMessageReference(6); - - list.addMessageFirst(new TestMessageReference(1)); - list.addMessageFirst(new TestMessageReference(2)); - list.addMessageFirst(new TestMessageReference(3)); - list.addMessageFirst(new TestMessageReference(4)); - list.addMessageFirst(new TestMessageReference(5)); - - assertTrue(list.size() == 5); - - list.addMessageLast(toRemove); - list.remove(toRemove); - - assertTrue(list.size() == 5); - - list.remove(toRemove); - - assertTrue(list.size() == 5); - - Iterator iter = list.iterator(); - int lastId = list.size(); - while (iter.hasNext()) { - assertEquals(lastId--, iter.next().getMessageId().getProducerSequenceId()); - } - - list.remove(null); - } - - @Test - public void testSize() { - PrioritizedPendingList list = new PrioritizedPendingList(); - assertTrue(list.isEmpty()); - - assertTrue(list.size() == 0); - list.addMessageFirst(new TestMessageReference(1)); - assertTrue(list.size() == 1); - list.addMessageLast(new TestMessageReference(2)); - assertTrue(list.size() == 2); - list.addMessageFirst(new TestMessageReference(3)); - assertTrue(list.size() == 3); - list.addMessageLast(new TestMessageReference(4)); - assertTrue(list.size() == 4); - list.addMessageFirst(new TestMessageReference(5)); - assertTrue(list.size() == 5); - - assertFalse(list.isEmpty()); - list.clear(); - assertTrue(list.isEmpty()); - assertTrue(list.size() == 0); - } - - @Test - public void testPrioritization() { - PrioritizedPendingList list = new PrioritizedPendingList(); - - list.addMessageFirst(new TestMessageReference(1, 5)); - list.addMessageFirst(new TestMessageReference(2, 4)); - list.addMessageFirst(new TestMessageReference(3, 3)); - list.addMessageFirst(new TestMessageReference(4, 2)); - list.addMessageFirst(new TestMessageReference(5, 1)); - - assertTrue(list.size() == 5); - - Iterator iter = list.iterator(); - int lastId = list.size(); - while (iter.hasNext()) { - assertEquals(lastId--, iter.next().getMessage().getPriority()); - } - } - - static class TestMessageReference implements MessageReference { - - @Override - public boolean canProcessAsExpired() { - return false; - } - - private static final IdGenerator id = new IdGenerator(); - - private Message message; - private MessageId messageId; - private int referenceCount = 0; - - public TestMessageReference(int sequenceId) { - messageId = new MessageId(id.generateId() + ":1", sequenceId); - message = new ActiveMQMessage(); - message.setPriority((byte) javax.jms.Message.DEFAULT_PRIORITY); - } - - public TestMessageReference(int sequenceId, int priority) { - messageId = new MessageId(id.generateId() + ":1", sequenceId); - message = new ActiveMQMessage(); - message.setPriority((byte) priority); - } - - @Override - public MessageId getMessageId() { - return messageId; - } - - @Override - public Message getMessageHardRef() { - return null; - } - - @Override - public Message getMessage() { - return message; - } - - @Override - public boolean isPersistent() { - return false; - } - - @Override - public Destination getRegionDestination() { - return null; - } - - @Override - public int getRedeliveryCounter() { - return 0; - } - - @Override - public void incrementRedeliveryCounter() { - } - - @Override - public int getReferenceCount() { - return this.referenceCount; - } - - @Override - public int incrementReferenceCount() { - return this.referenceCount++; - } - - @Override - public int decrementReferenceCount() { - return this.referenceCount--; - } - - @Override - public ConsumerId getTargetConsumerId() { - return null; - } - - @Override - public int getSize() { - return 1; - } - - @Override - public long getExpiration() { - return 0; - } - - @Override - public String getGroupID() { - return null; - } - - @Override - public int getGroupSequence() { - return 0; - } - - @Override - public boolean isExpired() { - return false; - } - - @Override - public boolean isDropped() { - return false; - } - - @Override - public boolean isAdvisory() { - return false; - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreBasedCursorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreBasedCursorTest.java deleted file mode 100644 index 0936144dd4..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreBasedCursorTest.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.activemq.broker.region.cursors; - -/** - * A StoreBasedCursorTest - * - */ - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.util.Date; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.usage.SystemUsage; - -public class StoreBasedCursorTest extends TestCase { - - protected String bindAddress = "tcp://localhost:60706"; - BrokerService broker; - ActiveMQConnectionFactory factory; - Connection connection; - Session session; - Queue queue; - int messageSize = 1024; - // actual message is messageSize*2, and 4*MessageSize would allow 2 messages be delivered, but the flush of the cache is async so the flush - // triggered on 2nd message maxing out the usage may not be in effect for the 3rd message to succeed. Making the memory usage more lenient - // gives the usageChange listener in the cursor an opportunity to kick in. - int memoryLimit = 12 * messageSize; - - @Override - protected void setUp() throws Exception { - super.setUp(); - if (broker == null) { - broker = new BrokerService(); - broker.setAdvisorySupport(false); - } - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - if (broker != null) { - broker.stop(); - broker = null; - } - } - - protected void start() throws Exception { - broker.start(); - factory = new ActiveMQConnectionFactory("vm://localhost?jms.alwaysSyncSend=true"); - factory.setWatchTopicAdvisories(false); - connection = factory.createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - queue = session.createQueue("QUEUE." + this.getClass().getName()); - } - - protected void stop() throws Exception { - session.close(); - connection.close(); - broker.stop(); - broker = null; - } - - protected void configureBroker(long memoryLimit, long systemLimit) throws Exception { - broker.setDeleteAllMessagesOnStartup(true); - broker.addConnector(bindAddress); - broker.setPersistent(true); - - SystemUsage systemUsage = broker.getSystemUsage(); - systemUsage.setSendFailIfNoSpace(true); - systemUsage.getMemoryUsage().setLimit(systemLimit); - - PolicyEntry policy = new PolicyEntry(); - policy.setProducerFlowControl(true); - policy.setUseCache(true); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); - } - - protected String createMessageText(int index) { - StringBuffer buffer = new StringBuffer(messageSize); - buffer.append("Message: " + index + " sent at: " + new Date()); - if (buffer.length() > messageSize) { - return buffer.substring(0, messageSize); - } - for (int i = buffer.length(); i < messageSize; i++) { - buffer.append(' '); - } - return buffer.toString(); - } - - protected void sendMessages(int deliveryMode) throws Exception { - start(); - MessageProducer producer = session.createProducer(queue); - producer.setDeliveryMode(deliveryMode); - int i = 0; - try { - for (i = 0; i < 200; i++) { - TextMessage message = session.createTextMessage(createMessageText(i)); - producer.send(message); - } - } catch (javax.jms.ResourceAllocationException e) { - e.printStackTrace(); - fail(e.getMessage() + " num msgs = " + i + ". percentUsage = " + broker.getSystemUsage().getMemoryUsage().getPercentUsage()); - } - stop(); - } - - // use QueueStorePrefetch - public void testTwoUsageEqualPersistent() throws Exception { - configureBroker(memoryLimit, memoryLimit); - sendMessages(DeliveryMode.PERSISTENT); - } - - public void testUseCachePersistent() throws Exception { - int limit = memoryLimit / 2; - configureBroker(limit, memoryLimit); - sendMessages(DeliveryMode.PERSISTENT); - } - - public void testMemoryUsageLowPersistent() throws Exception { - configureBroker(memoryLimit, 10 * memoryLimit); - sendMessages(DeliveryMode.PERSISTENT); - } - - // use FilePendingMessageCursor - public void testTwoUsageEqualNonPersistent() throws Exception { - configureBroker(memoryLimit, memoryLimit); - sendMessages(DeliveryMode.NON_PERSISTENT); - } - - public void testMemoryUsageLowNonPersistent() throws Exception { - configureBroker(memoryLimit, 10 * memoryLimit); - sendMessages(DeliveryMode.NON_PERSISTENT); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorJDBCNoDuplicateTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorJDBCNoDuplicateTest.java deleted file mode 100644 index f13b70436b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorJDBCNoDuplicateTest.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.activemq.broker.region.cursors; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.store.PersistenceAdapter; -import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; - -/** - * @author gtully - * @see https://issues.apache.org/activemq/browse/AMQ-2020 - */ -public class StoreQueueCursorJDBCNoDuplicateTest extends StoreQueueCursorNoDuplicateTest { - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - PersistenceAdapter persistenceAdapter = new JDBCPersistenceAdapter(); - broker.setPersistenceAdapter(persistenceAdapter); - return broker; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorKahaDBNoDuplicateTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorKahaDBNoDuplicateTest.java deleted file mode 100644 index eb679e1918..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorKahaDBNoDuplicateTest.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.activemq.broker.region.cursors; - -import java.io.File; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.store.PersistenceAdapter; -import org.apache.activemq.store.kahadb.KahaDBStore; - -/** - * @author gtully - * @see https://issues.apache.org/activemq/browse/AMQ-2020 - */ -public class StoreQueueCursorKahaDBNoDuplicateTest extends StoreQueueCursorNoDuplicateTest { - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - PersistenceAdapter persistenceAdapter = new KahaDBStore(); - persistenceAdapter.setDirectory(new File("target/activemq-data/kahadb")); - broker.setPersistenceAdapter(persistenceAdapter); - return broker; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorLevelDBNoDuplicateTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorLevelDBNoDuplicateTest.java deleted file mode 100644 index 05f801ce9b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorLevelDBNoDuplicateTest.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.activemq.broker.region.cursors; - -import java.io.File; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.leveldb.LevelDBStore; - -/** - * @author gtully - * @see https://issues.apache.org/activemq/browse/AMQ-2020 - */ -public class StoreQueueCursorLevelDBNoDuplicateTest extends StoreQueueCursorNoDuplicateTest { - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - LevelDBStore store = new LevelDBStore(); - store.setDirectory(new File("target/activemq-data/leveldb")); - broker.setPersistenceAdapter(store); - return broker; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorMemoryNoDuplicateTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorMemoryNoDuplicateTest.java deleted file mode 100644 index b5c6dddf99..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorMemoryNoDuplicateTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.broker.region.cursors; - -import org.apache.activemq.broker.BrokerService; - -/** - * @author gtully - * @see https://issues.apache.org/activemq/browse/AMQ-2020 - */ -public class StoreQueueCursorMemoryNoDuplicateTest extends StoreQueueCursorNoDuplicateTest { - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - broker.setPersistent(false); - return broker; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorNoDuplicateTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorNoDuplicateTest.java deleted file mode 100644 index f783ffaf58..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorNoDuplicateTest.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.activemq.broker.region.cursors; - -import junit.framework.TestCase; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.ConnectionContext; -import org.apache.activemq.broker.region.DestinationStatistics; -import org.apache.activemq.broker.region.MessageReference; -import org.apache.activemq.broker.region.Queue; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTextMessage; -import org.apache.activemq.command.ConsumerInfo; -import org.apache.activemq.command.MessageId; -import org.apache.activemq.store.MessageStore; -import org.apache.activemq.store.PersistenceAdapter; -import org.apache.activemq.usage.SystemUsage; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author gtully - * https://issues.apache.org/activemq/browse/AMQ-2020 - */ -public class StoreQueueCursorNoDuplicateTest extends TestCase { - - static final Logger LOG = LoggerFactory.getLogger(StoreQueueCursorNoDuplicateTest.class); - ActiveMQQueue destination = new ActiveMQQueue("queue-" + StoreQueueCursorNoDuplicateTest.class.getSimpleName()); - BrokerService brokerService; - - final static String mesageIdRoot = "11111:22222:0:"; - final int messageBytesSize = 1024; - final String text = new String(new byte[messageBytesSize]); - - protected int count = 6; - - @Override - public void setUp() throws Exception { - brokerService = createBroker(); - brokerService.setUseJmx(false); - brokerService.deleteAllMessages(); - brokerService.start(); - } - - protected BrokerService createBroker() throws Exception { - return new BrokerService(); - } - - @Override - public void tearDown() throws Exception { - brokerService.stop(); - } - - public void testNoDuplicateAfterCacheFullAndReadPast() throws Exception { - final PersistenceAdapter persistenceAdapter = brokerService.getPersistenceAdapter(); - final MessageStore queueMessageStore = persistenceAdapter.createQueueMessageStore(destination); - final ConsumerInfo consumerInfo = new ConsumerInfo(); - final DestinationStatistics destinationStatistics = new DestinationStatistics(); - consumerInfo.setExclusive(true); - - final Queue queue = new Queue(brokerService, destination, queueMessageStore, destinationStatistics, null); - - queueMessageStore.start(); - queueMessageStore.registerIndexListener(null); - - QueueStorePrefetch underTest = new QueueStorePrefetch(queue, brokerService.getBroker()); - SystemUsage systemUsage = new SystemUsage(); - // ensure memory limit is reached - systemUsage.getMemoryUsage().setLimit(messageBytesSize * (count + 2)); - underTest.setSystemUsage(systemUsage); - underTest.setEnableAudit(false); - underTest.start(); - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - - final ConnectionContext contextNotInTx = new ConnectionContext(); - for (int i = 0; i < count; i++) { - ActiveMQTextMessage msg = getMessage(i); - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - - queueMessageStore.addMessage(contextNotInTx, msg); - underTest.addMessageLast(msg); - } - - assertTrue("cache is disabled as limit reached", !underTest.isCacheEnabled()); - int dequeueCount = 0; - - underTest.setMaxBatchSize(2); - underTest.reset(); - while (underTest.hasNext() && dequeueCount < count) { - MessageReference ref = underTest.next(); - ref.decrementReferenceCount(); - underTest.remove(); - LOG.info("Received message: {} with body: {}", ref.getMessageId(), ((ActiveMQTextMessage) ref.getMessage()).getText()); - assertEquals(dequeueCount++, ref.getMessageId().getProducerSequenceId()); - } - underTest.release(); - assertEquals(count, dequeueCount); - } - - private ActiveMQTextMessage getMessage(int i) throws Exception { - ActiveMQTextMessage message = new ActiveMQTextMessage(); - MessageId id = new MessageId(mesageIdRoot + i); - id.setBrokerSequenceId(i); - id.setProducerSequenceId(i); - message.setMessageId(id); - message.setDestination(destination); - message.setPersistent(true); - message.setResponseRequired(true); - message.setText("Msg:" + i + " " + text); - assertEquals(message.getMessageId().getProducerSequenceId(), i); - return message; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorOrderTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorOrderTest.java deleted file mode 100644 index c3dc38b828..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/cursors/StoreQueueCursorOrderTest.java +++ /dev/null @@ -1,507 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.broker.region.cursors; - -import java.io.IOException; -import java.util.concurrent.Executors; -import java.util.concurrent.FutureTask; -import java.util.concurrent.atomic.AtomicLong; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.ConnectionContext; -import org.apache.activemq.broker.region.DestinationStatistics; -import org.apache.activemq.broker.region.MessageReference; -import org.apache.activemq.broker.region.Queue; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTextMessage; -import org.apache.activemq.command.ConsumerInfo; -import org.apache.activemq.command.Message; -import org.apache.activemq.command.MessageAck; -import org.apache.activemq.command.MessageId; -import org.apache.activemq.store.AbstractMessageStore; -import org.apache.activemq.store.MessageRecoveryListener; -import org.apache.activemq.usage.SystemUsage; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class StoreQueueCursorOrderTest { - - private static final Logger LOG = LoggerFactory.getLogger(StoreQueueCursorOrderTest.class); - - ActiveMQQueue destination = new ActiveMQQueue("queue-" + StoreQueueCursorOrderTest.class.getSimpleName()); - BrokerService brokerService; - - final static String mesageIdRoot = "11111:22222:0:"; - final int messageBytesSize = 1024; - final String text = new String(new byte[messageBytesSize]); - - @Before - public void setUp() throws Exception { - brokerService = createBroker(); - brokerService.setUseJmx(false); - brokerService.deleteAllMessages(); - brokerService.start(); - } - - protected BrokerService createBroker() throws Exception { - return new BrokerService(); - } - - @After - public void tearDown() throws Exception { - brokerService.stop(); - } - - @Test - public void tesBlockedFuture() throws Exception { - final int count = 2; - final Message[] messages = new Message[count]; - final TestMessageStore queueMessageStore = new TestMessageStore(messages, destination); - final ConsumerInfo consumerInfo = new ConsumerInfo(); - final DestinationStatistics destinationStatistics = new DestinationStatistics(); - consumerInfo.setExclusive(true); - - final Queue queue = new Queue(brokerService, destination, queueMessageStore, destinationStatistics, null); - - queueMessageStore.start(); - queueMessageStore.registerIndexListener(null); - - QueueStorePrefetch underTest = new QueueStorePrefetch(queue, brokerService.getBroker()); - SystemUsage systemUsage = new SystemUsage(); - // ensure memory limit is reached - systemUsage.getMemoryUsage().setLimit(messageBytesSize * 1); - underTest.setSystemUsage(systemUsage); - underTest.setEnableAudit(false); - underTest.start(); - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - - ActiveMQTextMessage msg = getMessage(0); - messages[1] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.setRecievedByDFBridge(true); - FutureTask future = new FutureTask(new Runnable() { - @Override - public void run() { - } - }, 2L) { - }; - msg.getMessageId().setFutureOrSequenceLong(future); - underTest.addMessageLast(msg); - - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - - // second message will flip the cache but will be stored before the future task - msg = getMessage(1); - messages[0] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.getMessageId().setFutureOrSequenceLong(1L); - underTest.addMessageLast(msg); - - assertTrue("cache is disabled as limit reached", !underTest.isCacheEnabled()); - assertEquals("setBatch unset", 0L, queueMessageStore.batch.get()); - - int dequeueCount = 0; - - underTest.setMaxBatchSize(2); - underTest.reset(); - while (underTest.hasNext() && dequeueCount < count) { - MessageReference ref = underTest.next(); - ref.decrementReferenceCount(); - underTest.remove(); - LOG.info("Received message: {} with body: {}", ref.getMessageId(), ((ActiveMQTextMessage) ref.getMessage()).getText()); - assertEquals(dequeueCount++, ref.getMessageId().getProducerSequenceId()); - } - underTest.release(); - assertEquals(count, dequeueCount); - } - - @Test - public void testNoSetBatchWithUnOrderedFutureCurrentSync() throws Exception { - final int count = 2; - final Message[] messages = new Message[count]; - final TestMessageStore queueMessageStore = new TestMessageStore(messages, destination); - final ConsumerInfo consumerInfo = new ConsumerInfo(); - final DestinationStatistics destinationStatistics = new DestinationStatistics(); - consumerInfo.setExclusive(true); - - final Queue queue = new Queue(brokerService, destination, queueMessageStore, destinationStatistics, null); - - queueMessageStore.start(); - queueMessageStore.registerIndexListener(null); - - QueueStorePrefetch underTest = new QueueStorePrefetch(queue, brokerService.getBroker()); - SystemUsage systemUsage = new SystemUsage(); - // ensure memory limit is reached - systemUsage.getMemoryUsage().setLimit(messageBytesSize * 1); - underTest.setSystemUsage(systemUsage); - underTest.setEnableAudit(false); - underTest.start(); - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - - ActiveMQTextMessage msg = getMessage(0); - messages[1] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.setRecievedByDFBridge(true); - final ActiveMQTextMessage msgRef = msg; - FutureTask future = new FutureTask(new Runnable() { - @Override - public void run() { - msgRef.getMessageId().setFutureOrSequenceLong(1L); - } - }, 1L) { - }; - msg.getMessageId().setFutureOrSequenceLong(future); - Executors.newSingleThreadExecutor().submit(future); - underTest.addMessageLast(msg); - - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - - // second message will flip the cache but will be stored before the future task - msg = getMessage(1); - messages[0] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.getMessageId().setFutureOrSequenceLong(1L); - underTest.addMessageLast(msg); - - assertTrue("cache is disabled as limit reached", !underTest.isCacheEnabled()); - assertEquals("setBatch unset", 0L, queueMessageStore.batch.get()); - - int dequeueCount = 0; - - underTest.setMaxBatchSize(2); - underTest.reset(); - while (underTest.hasNext() && dequeueCount < count) { - MessageReference ref = underTest.next(); - ref.decrementReferenceCount(); - underTest.remove(); - LOG.info("Received message: {} with body: {}", ref.getMessageId(), ((ActiveMQTextMessage) ref.getMessage()).getText()); - assertEquals(dequeueCount++, ref.getMessageId().getProducerSequenceId()); - } - underTest.release(); - assertEquals(count, dequeueCount); - } - - @Test - public void testSetBatchWithOrderedFutureCurrentFuture() throws Exception { - final int count = 2; - final Message[] messages = new Message[count]; - final TestMessageStore queueMessageStore = new TestMessageStore(messages, destination); - final ConsumerInfo consumerInfo = new ConsumerInfo(); - final DestinationStatistics destinationStatistics = new DestinationStatistics(); - consumerInfo.setExclusive(true); - - final Queue queue = new Queue(brokerService, destination, queueMessageStore, destinationStatistics, null); - - queueMessageStore.start(); - queueMessageStore.registerIndexListener(null); - - QueueStorePrefetch underTest = new QueueStorePrefetch(queue, brokerService.getBroker()); - SystemUsage systemUsage = new SystemUsage(); - // ensure memory limit is reached - systemUsage.getMemoryUsage().setLimit(messageBytesSize * 1); - underTest.setSystemUsage(systemUsage); - underTest.setEnableAudit(false); - underTest.start(); - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - - ActiveMQTextMessage msg = getMessage(0); - messages[0] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.setRecievedByDFBridge(true); - final ActiveMQTextMessage msgRef = msg; - FutureTask future = new FutureTask(new Runnable() { - @Override - public void run() { - msgRef.getMessageId().setFutureOrSequenceLong(0L); - } - }, 0L) { - }; - msg.getMessageId().setFutureOrSequenceLong(future); - Executors.newSingleThreadExecutor().submit(future); - underTest.addMessageLast(msg); - - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - - // second message will flip the cache but will be stored before the future task - msg = getMessage(1); - messages[1] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.setRecievedByDFBridge(true); - final ActiveMQTextMessage msgRe2f = msg; - FutureTask future2 = new FutureTask(new Runnable() { - @Override - public void run() { - msgRe2f.getMessageId().setFutureOrSequenceLong(1L); - } - }, 1L) { - }; - msg.getMessageId().setFutureOrSequenceLong(future2); - Executors.newSingleThreadExecutor().submit(future2); - underTest.addMessageLast(msg); - - assertTrue("cache is disabled as limit reached", !underTest.isCacheEnabled()); - assertEquals("setBatch set", 1L, queueMessageStore.batch.get()); - - int dequeueCount = 0; - - underTest.setMaxBatchSize(2); - underTest.reset(); - while (underTest.hasNext() && dequeueCount < count) { - MessageReference ref = underTest.next(); - ref.decrementReferenceCount(); - underTest.remove(); - LOG.info("Received message: {} with body: {}", ref.getMessageId(), ((ActiveMQTextMessage) ref.getMessage()).getText()); - assertEquals(dequeueCount++, ref.getMessageId().getProducerSequenceId()); - } - underTest.release(); - assertEquals(count, dequeueCount); - } - - @Test - public void testSetBatchWithFuture() throws Exception { - final int count = 4; - final Message[] messages = new Message[count]; - final TestMessageStore queueMessageStore = new TestMessageStore(messages, destination); - final ConsumerInfo consumerInfo = new ConsumerInfo(); - final DestinationStatistics destinationStatistics = new DestinationStatistics(); - consumerInfo.setExclusive(true); - - final Queue queue = new Queue(brokerService, destination, queueMessageStore, destinationStatistics, null); - - queueMessageStore.start(); - queueMessageStore.registerIndexListener(null); - - QueueStorePrefetch underTest = new QueueStorePrefetch(queue, brokerService.getBroker()); - SystemUsage systemUsage = new SystemUsage(); - // ensure memory limit is reached - systemUsage.getMemoryUsage().setLimit(messageBytesSize * (count + 6)); - underTest.setSystemUsage(systemUsage); - underTest.setEnableAudit(false); - underTest.start(); - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - - ActiveMQTextMessage msg = getMessage(0); - messages[0] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.setRecievedByDFBridge(true); - final ActiveMQTextMessage msgRef = msg; - FutureTask future0 = new FutureTask(new Runnable() { - @Override - public void run() { - msgRef.getMessageId().setFutureOrSequenceLong(0L); - } - }, 0L) { - }; - msg.getMessageId().setFutureOrSequenceLong(future0); - underTest.addMessageLast(msg); - Executors.newSingleThreadExecutor().submit(future0); - - msg = getMessage(1); - messages[3] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.setRecievedByDFBridge(true); - final ActiveMQTextMessage msgRef1 = msg; - FutureTask future1 = new FutureTask(new Runnable() { - @Override - public void run() { - msgRef1.getMessageId().setFutureOrSequenceLong(3L); - } - }, 3L) { - }; - msg.getMessageId().setFutureOrSequenceLong(future1); - underTest.addMessageLast(msg); - - msg = getMessage(2); - messages[1] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.getMessageId().setFutureOrSequenceLong(1L); - underTest.addMessageLast(msg); - - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - - // out of order future - Executors.newSingleThreadExecutor().submit(future1); - - // sync add to flip cache - msg = getMessage(3); - messages[2] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.getMessageId().setFutureOrSequenceLong(3L); - underTest.addMessageLast(msg); - - assertTrue("cache is disabled as limit reached", !underTest.isCacheEnabled()); - assertEquals("setBatch set", 2L, queueMessageStore.batch.get()); - - int dequeueCount = 0; - - underTest.setMaxBatchSize(count); - underTest.reset(); - while (underTest.hasNext() && dequeueCount < count) { - MessageReference ref = underTest.next(); - ref.decrementReferenceCount(); - underTest.remove(); - LOG.info("Received message: {} with body: {}", ref.getMessageId(), ((ActiveMQTextMessage) ref.getMessage()).getText()); - assertEquals(dequeueCount++, ref.getMessageId().getProducerSequenceId()); - } - underTest.release(); - assertEquals(count, dequeueCount); - } - - @Test - public void testSetBatch() throws Exception { - final int count = 3; - final Message[] messages = new Message[count]; - final TestMessageStore queueMessageStore = new TestMessageStore(messages, destination); - final ConsumerInfo consumerInfo = new ConsumerInfo(); - final DestinationStatistics destinationStatistics = new DestinationStatistics(); - consumerInfo.setExclusive(true); - - final Queue queue = new Queue(brokerService, destination, queueMessageStore, destinationStatistics, null); - - queueMessageStore.start(); - queueMessageStore.registerIndexListener(null); - - QueueStorePrefetch underTest = new QueueStorePrefetch(queue, brokerService.getBroker()); - SystemUsage systemUsage = new SystemUsage(); - // ensure memory limit is reached - systemUsage.getMemoryUsage().setLimit(messageBytesSize * 5); - underTest.setSystemUsage(systemUsage); - underTest.setEnableAudit(false); - underTest.start(); - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - - ActiveMQTextMessage msg = getMessage(0); - messages[0] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.getMessageId().setFutureOrSequenceLong(0L); - underTest.addMessageLast(msg); - - msg = getMessage(1); - messages[1] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.getMessageId().setFutureOrSequenceLong(1L); - underTest.addMessageLast(msg); - - assertTrue("cache enabled", underTest.isUseCache() && underTest.isCacheEnabled()); - - msg = getMessage(2); - messages[2] = msg; - msg.setMemoryUsage(systemUsage.getMemoryUsage()); - msg.getMessageId().setFutureOrSequenceLong(2L); - underTest.addMessageLast(msg); - - assertTrue("cache is disabled as limit reached", !underTest.isCacheEnabled()); - assertEquals("setBatch set", 2L, queueMessageStore.batch.get()); - - int dequeueCount = 0; - - underTest.setMaxBatchSize(2); - underTest.reset(); - while (underTest.hasNext() && dequeueCount < count) { - MessageReference ref = underTest.next(); - ref.decrementReferenceCount(); - underTest.remove(); - LOG.info("Received message: {} with body: {}", ref.getMessageId(), ((ActiveMQTextMessage) ref.getMessage()).getText()); - assertEquals(dequeueCount++, ref.getMessageId().getProducerSequenceId()); - } - underTest.release(); - assertEquals(count, dequeueCount); - } - - private ActiveMQTextMessage getMessage(int i) throws Exception { - ActiveMQTextMessage message = new ActiveMQTextMessage(); - MessageId id = new MessageId(mesageIdRoot + i); - id.setBrokerSequenceId(i); - id.setProducerSequenceId(i); - message.setMessageId(id); - message.setDestination(destination); - message.setPersistent(true); - message.setResponseRequired(true); - message.setText("Msg:" + i + " " + text); - assertEquals(message.getMessageId().getProducerSequenceId(), i); - return message; - } - - class TestMessageStore extends AbstractMessageStore { - - final Message[] messages; - public AtomicLong batch = new AtomicLong(); - - public TestMessageStore(Message[] messages, ActiveMQDestination dest) { - super(dest); - this.messages = messages; - } - - @Override - public void addMessage(ConnectionContext context, Message message) throws IOException { - - } - - @Override - public Message getMessage(MessageId identity) throws IOException { - return null; - } - - @Override - public void removeMessage(ConnectionContext context, MessageAck ack) throws IOException { - - } - - @Override - public void removeAllMessages(ConnectionContext context) throws IOException { - - } - - @Override - public void recover(MessageRecoveryListener container) throws Exception { - - } - - @Override - public int getMessageCount() throws IOException { - return 0; - } - - @Override - public void resetBatching() { - - } - - @Override - public void recoverNextMessages(int maxReturned, MessageRecoveryListener listener) throws Exception { - for (int i = batch.intValue(); i < messages.length; i++) { - LOG.info("recovered index:" + i); - listener.recoverMessage(messages[i]); - } - } - - @Override - public void setBatch(MessageId message) { - batch.set((Long) message.getFutureOrSequenceLong()); - batch.incrementAndGet(); - } - - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupHashBucketTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupHashBucketTest.java deleted file mode 100644 index 5a5f3f8414..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupHashBucketTest.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.activemq.broker.region.group; - -/** - * - * - */ -public class MessageGroupHashBucketTest extends MessageGroupMapTest { - - @Override - protected MessageGroupMap createMessageGroupMap() { - return new MessageGroupHashBucket(1024, 64); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupMapTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupMapTest.java deleted file mode 100644 index bcc21466e8..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupMapTest.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.activemq.broker.region.group; - -import junit.framework.TestCase; - -import org.apache.activemq.command.ConnectionId; -import org.apache.activemq.command.ConsumerId; -import org.apache.activemq.command.SessionId; - -/** - * - * - */ -public class MessageGroupMapTest extends TestCase { - - protected MessageGroupMap map; - private ConsumerId consumer1; - private ConsumerId consumer2; - private ConsumerId consumer3; - private long idCounter; - - public void testSingleConsumerForManyBucks() throws Exception { - assertGet("1", null); - - map.put("1", consumer1); - assertGet("1", consumer1); - map.put("2", consumer1); - assertGet("2", consumer1); - map.put("3", consumer1); - assertGet("3", consumer1); - - MessageGroupSet set = map.removeConsumer(consumer1); - assertContains(set, "1"); - assertContains(set, "2"); - assertContains(set, "3"); - assertGet("1", null); - assertGet("2", null); - assertGet("3", null); - } - - public void testManyConsumers() throws Exception { - assertGet("1", null); - - map.put("1", consumer1); - assertGet("1", consumer1); - map.put("2", consumer2); - assertGet("2", consumer2); - map.put("3", consumer3); - assertGet("3", consumer3); - - MessageGroupSet set = map.removeConsumer(consumer1); - assertContains(set, "1"); - - assertGet("1", null); - map.put("1", consumer2); - assertGet("1", consumer2); - - set = map.removeConsumer(consumer2); - assertContains(set, "1"); - assertContains(set, "2"); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - map = createMessageGroupMap(); - consumer1 = createConsumerId(); - consumer2 = createConsumerId(); - consumer3 = createConsumerId(); - } - - protected MessageGroupMap createMessageGroupMap() { - return new SimpleMessageGroupMap(); - } - - protected ConsumerId createConsumerId() { - ConnectionId connectionId = new ConnectionId("" + ++idCounter); - SessionId sessionId = new SessionId(connectionId, ++idCounter); - ConsumerId answer = new ConsumerId(sessionId, ++idCounter); - return answer; - } - - protected void assertGet(String groupdId, ConsumerId expected) { - ConsumerId actual = map.get(groupdId); - assertEquals("Entry for groupId: " + groupdId, expected, actual); - } - - protected void assertContains(MessageGroupSet set, String groupID) { - assertTrue("MessageGroup set: " + set + " does not contain groupID: " + groupID, set.contains(groupID)); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupTest.java deleted file mode 100644 index a8101f7541..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupTest.java +++ /dev/null @@ -1,179 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.region.group; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; - -import org.apache.activemq.CombinationTestSupport; -import org.apache.activemq.JmsTestSupport; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MessageGroupTest extends JmsTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(CombinationTestSupport.class); - - public void testGroupedMessagesDeliveredToOnlyOneConsumer() throws Exception { - - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - - // Setup a first connection - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer1 = session.createConsumer(destination); - MessageProducer producer = session.createProducer(destination); - - // Send the messages. - for (int i = 0; i < 4; i++) { - TextMessage message = session.createTextMessage("message " + i); - message.setStringProperty("JMSXGroupID", "TEST-GROUP"); - message.setIntProperty("JMSXGroupSeq", i + 1); - LOG.info("sending message: " + message); - producer.send(message); - } - - // All the messages should have been sent down connection 1.. just get - // the first 3 - for (int i = 0; i < 3; i++) { - TextMessage m1 = (TextMessage) consumer1.receive(500); - assertNotNull("m1 is null for index: " + i, m1); - assertEquals(m1.getIntProperty("JMSXGroupSeq"), i + 1); - } - - // Setup a second connection - Connection connection1 = factory.createConnection(userName, password); - connection1.start(); - Session session2 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer2 = session2.createConsumer(destination); - - // Close the first consumer. - consumer1.close(); - - // The last messages should now go the the second consumer. - for (int i = 0; i < 1; i++) { - TextMessage m1 = (TextMessage) consumer2.receive(500); - assertNotNull("m1 is null for index: " + i, m1); - assertEquals(m1.getIntProperty("JMSXGroupSeq"), 4 + i); - } - - //assert that there are no other messages left for the consumer 2 - Message m = consumer2.receive(100); - assertNull("consumer 2 has some messages left", m); - } - - public void testAddingConsumer() throws Exception { - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - - // Setup a first connection - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageProducer producer = session.createProducer(destination); - //MessageConsumer consumer = session.createConsumer(destination); - - TextMessage message = session.createTextMessage("message"); - message.setStringProperty("JMSXGroupID", "TEST-GROUP"); - - LOG.info("sending message: " + message); - producer.send(message); - - MessageConsumer consumer = session.createConsumer(destination); - - TextMessage msg = (TextMessage) consumer.receive(); - assertNotNull(msg); - boolean first = msg.getBooleanProperty("JMSXGroupFirstForConsumer"); - assertTrue(first); - } - - public void testClosingMessageGroup() throws Exception { - - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - - // Setup a first connection - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer1 = session.createConsumer(destination); - MessageProducer producer = session.createProducer(destination); - - // Send the messages. - for (int i = 0; i < 4; i++) { - TextMessage message = session.createTextMessage("message " + i); - message.setStringProperty("JMSXGroupID", "TEST-GROUP"); - LOG.info("sending message: " + message); - producer.send(message); - } - - // All the messages should have been sent down consumer1.. just get - // the first 3 - for (int i = 0; i < 3; i++) { - TextMessage m1 = (TextMessage) consumer1.receive(500); - assertNotNull("m1 is null for index: " + i, m1); - } - - // Setup a second consumer - Connection connection1 = factory.createConnection(userName, password); - connection1.start(); - Session session2 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer2 = session2.createConsumer(destination); - - //assert that there are no messages for the consumer 2 - Message m = consumer2.receive(100); - assertNull("consumer 2 has some messages", m); - - // Close the group - TextMessage message = session.createTextMessage("message " + 5); - message.setStringProperty("JMSXGroupID", "TEST-GROUP"); - message.setIntProperty("JMSXGroupSeq", -1); - LOG.info("sending message: " + message); - producer.send(message); - - //Send some more messages - for (int i = 0; i < 4; i++) { - message = session.createTextMessage("message " + i); - message.setStringProperty("JMSXGroupID", "TEST-GROUP"); - LOG.info("sending message: " + message); - producer.send(message); - } - - // Receive the fourth message - TextMessage m1 = (TextMessage) consumer1.receive(500); - assertNotNull("m1 is null for index: " + 4, m1); - - // Receive the closing message - m1 = (TextMessage) consumer1.receive(500); - assertNotNull("m1 is null for index: " + 5, m1); - - //assert that there are no messages for the consumer 1 - m = consumer1.receive(100); - assertNull("consumer 1 has some messages left: " + m, m); - - // The messages should now go to the second consumer. - for (int i = 0; i < 4; i++) { - m1 = (TextMessage) consumer2.receive(500); - assertNotNull("m1 is null for index: " + i, m1); - } - - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JmsCronSchedulerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JmsCronSchedulerTest.java deleted file mode 100644 index f4c7d3d302..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JmsCronSchedulerTest.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.activemq.broker.scheduler; - -import javax.jms.Connection; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.util.Date; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.activemq.ScheduledMessage; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -public class JmsCronSchedulerTest extends JobSchedulerTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(JmsCronSchedulerTest.class); - - @Test - public void testSimulatenousCron() throws Exception { - - final int COUNT = 10; - final AtomicInteger count = new AtomicInteger(); - Connection connection = createConnection(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageConsumer consumer = session.createConsumer(destination); - - final CountDownLatch latch = new CountDownLatch(COUNT); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - count.incrementAndGet(); - latch.countDown(); - assertTrue(message instanceof TextMessage); - TextMessage tm = (TextMessage) message; - try { - LOG.info("Received [{}] count: {} ", tm.getText(), count.get()); - } catch (JMSException e) { - LOG.error("Unexpected exception in onMessage", e); - fail("Unexpected exception in onMessage: " + e.getMessage()); - } - } - }); - - connection.start(); - for (int i = 0; i < COUNT; i++) { - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage("test msg " + i); - message.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_CRON, "* * * * *"); - producer.send(message); - LOG.info("Message {} sent at {}", i, new Date().toString()); - producer.close(); - //wait a couple sec so cron start time is different for next message - Thread.sleep(2000); - } - SchedulerBroker sb = (SchedulerBroker) this.broker.getBroker().getAdaptor(SchedulerBroker.class); - JobScheduler js = sb.getJobScheduler(); - List list = js.getAllJobs(); - assertEquals(COUNT, list.size()); - latch.await(2, TimeUnit.MINUTES); - //All should messages should have been received by now - assertEquals(COUNT, count.get()); - } - - @Test - public void testCronScheduleWithTtlSet() throws Exception { - - Connection connection = createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - connection.start(); - - MessageProducer producer = session.createProducer(destination); - producer.setTimeToLive(TimeUnit.MINUTES.toMillis(1)); - TextMessage message = session.createTextMessage("test msg "); - message.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_CRON, "* * * * *"); - - producer.send(message); - producer.close(); - - Thread.sleep(TimeUnit.MINUTES.toMillis(2)); - - assertNotNull(consumer.receiveNoWait()); - assertNull(consumer.receiveNoWait()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JmsSchedulerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JmsSchedulerTest.java deleted file mode 100644 index ba2a60d537..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JmsSchedulerTest.java +++ /dev/null @@ -1,286 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.scheduler; - -import javax.jms.Connection; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ScheduledMessage; -import org.apache.activemq.util.ProducerThread; -import org.apache.activemq.util.Wait; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -public class JmsSchedulerTest extends JobSchedulerTestSupport { - - @Test - public void testCron() throws Exception { - final int COUNT = 10; - final AtomicInteger count = new AtomicInteger(); - Connection connection = createConnection(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageConsumer consumer = session.createConsumer(destination); - - final CountDownLatch latch = new CountDownLatch(COUNT); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - count.incrementAndGet(); - } - }); - - connection.start(); - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage("test msg"); - long time = 1000; - message.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_CRON, "* * * * *"); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 500); - message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, COUNT - 1); - - producer.send(message); - producer.close(); - - Thread.sleep(500); - SchedulerBroker sb = (SchedulerBroker) this.broker.getBroker().getAdaptor(SchedulerBroker.class); - JobScheduler js = sb.getJobScheduler(); - List list = js.getAllJobs(); - assertEquals(1, list.size()); - latch.await(240, TimeUnit.SECONDS); - assertEquals(COUNT, count.get()); - } - - @Test - public void testSchedule() throws Exception { - final int COUNT = 1; - Connection connection = createConnection(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageConsumer consumer = session.createConsumer(destination); - - final CountDownLatch latch = new CountDownLatch(COUNT); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - } - }); - - connection.start(); - long time = 5000; - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage("test msg"); - - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - - producer.send(message); - producer.close(); - // make sure the message isn't delivered early - Thread.sleep(2000); - assertEquals(latch.getCount(), COUNT); - latch.await(5, TimeUnit.SECONDS); - assertEquals(latch.getCount(), 0); - } - - @Test - public void testTransactedSchedule() throws Exception { - final int COUNT = 1; - Connection connection = createConnection(); - - final Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - - MessageConsumer consumer = session.createConsumer(destination); - - final CountDownLatch latch = new CountDownLatch(COUNT); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - try { - session.commit(); - } catch (JMSException e) { - e.printStackTrace(); - } - latch.countDown(); - } - }); - - connection.start(); - long time = 5000; - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage("test msg"); - - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - - producer.send(message); - session.commit(); - producer.close(); - // make sure the message isn't delivered early - Thread.sleep(2000); - assertEquals(latch.getCount(), COUNT); - latch.await(5, TimeUnit.SECONDS); - assertEquals(latch.getCount(), 0); - } - - @Test - public void testScheduleRepeated() throws Exception { - final int NUMBER = 10; - final AtomicInteger count = new AtomicInteger(); - Connection connection = createConnection(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageConsumer consumer = session.createConsumer(destination); - - final CountDownLatch latch = new CountDownLatch(NUMBER); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - count.incrementAndGet(); - } - }); - - connection.start(); - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage("test msg"); - long time = 1000; - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 500); - message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, NUMBER - 1); - producer.send(message); - producer.close(); - assertEquals(latch.getCount(), NUMBER); - latch.await(10, TimeUnit.SECONDS); - assertEquals(0, latch.getCount()); - // wait a little longer - make sure we only get NUMBER of replays - Thread.sleep(1000); - assertEquals(NUMBER, count.get()); - } - - @Test - public void testScheduleRestart() throws Exception { - // send a message - Connection connection = createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - connection.start(); - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage("test msg"); - long time = 5000; - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - producer.send(message); - producer.close(); - - //restart broker - broker.stop(); - broker.waitUntilStopped(); - - broker = createBroker(false); - broker.start(); - broker.waitUntilStarted(); - - // consume the message - connection = createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - Message msg = consumer.receive(5000); - assertNotNull("Didn't receive the message", msg); - - //send another message - producer = session.createProducer(destination); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - producer.send(message); - producer.close(); - } - - @Test - public void testJobSchedulerStoreUsage() throws Exception { - - // Shrink the store limit down so we get the producer to block - broker.getSystemUsage().getJobSchedulerUsage().setLimit(10 * 1024); - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection conn = factory.createConnection(); - conn.start(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - final long time = 5000; - final ProducerThread producer = new ProducerThread(sess, destination) { - @Override - protected Message createMessage(int i) throws Exception { - Message message = super.createMessage(i); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - return message; - } - }; - producer.setMessageCount(100); - producer.start(); - - MessageConsumer consumer = sess.createConsumer(destination); - final CountDownLatch latch = new CountDownLatch(100); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - } - }); - - // wait for the producer to block, which should happen immediately, and also wait long - // enough for the delay to elapse. We should see no deliveries as the send should block - // on the first message. - Thread.sleep(10000L); - - assertEquals(100, latch.getCount()); - - // Increase the store limit so the producer unblocks. Everything should enqueue at this point. - broker.getSystemUsage().getJobSchedulerUsage().setLimit(1024 * 1024 * 33); - - // Wait long enough that the messages are enqueued and the delivery delay has elapsed. - Thread.sleep(10000L); - - // Make sure we sent all the messages we expected to send - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return producer.getSentCount() == producer.getMessageCount(); - } - }, 20000L); - - assertEquals("Producer didn't send all messages", producer.getMessageCount(), producer.getSentCount()); - - // Make sure we got all the messages we expected to get - latch.await(20000L, TimeUnit.MILLISECONDS); - - assertEquals("Consumer did not receive all messages.", 0, latch.getCount()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerBrokerShutdownTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerBrokerShutdownTest.java deleted file mode 100644 index 85698158fa..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerBrokerShutdownTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.scheduler; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.Session; -import java.io.File; - -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.ScheduledMessage; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.util.IOHelper; -import org.apache.activemq.util.ProducerThread; - -public class JobSchedulerBrokerShutdownTest extends EmbeddedBrokerTestSupport { - - @Override - protected BrokerService createBroker() throws Exception { - File schedulerDirectory = new File("target/scheduler"); - - IOHelper.mkdirs(schedulerDirectory); - IOHelper.deleteChildren(schedulerDirectory); - - BrokerService broker = super.createBroker(); - broker.setSchedulerSupport(true); - broker.setDataDirectory("target"); - broker.setSchedulerDirectoryFile(schedulerDirectory); - broker.getSystemUsage().getStoreUsage().setLimit(1 * 512); - broker.deleteAllMessages(); - return broker; - } - - @Override - protected boolean isPersistent() { - return true; - } - - public void testSchedule() throws Exception { - - Connection connection = createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - connection.start(); - final long time = 1000; - - ProducerThread producer = new ProducerThread(session, destination) { - @Override - protected Message createMessage(int i) throws Exception { - Message message = super.createMessage(i); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - return message; - } - }; - - producer.setMessageCount(200); - producer.setDaemon(true); - - producer.start(); - - Thread.sleep(5000); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerJmxManagementTests.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerJmxManagementTests.java deleted file mode 100644 index 388aaab600..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerJmxManagementTests.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.activemq.broker.scheduler; - -import javax.jms.Connection; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.management.openmbean.TabularData; -import java.util.List; - -import org.apache.activemq.ScheduledMessage; -import org.apache.activemq.broker.jmx.JobSchedulerViewMBean; -import org.apache.activemq.util.Wait; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -/** - * Tests of the JMX JobSchedulerStore management MBean. - */ -public class JobSchedulerJmxManagementTests extends JobSchedulerTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(JobSchedulerJmxManagementTests.class); - - @Test - public void testJobSchedulerMBeanIsRegistered() throws Exception { - JobSchedulerViewMBean view = getJobSchedulerMBean(); - assertNotNull(view); - assertTrue(view.getAllJobs().isEmpty()); - } - - @Test - public void testGetNumberOfJobs() throws Exception { - JobSchedulerViewMBean view = getJobSchedulerMBean(); - assertNotNull(view); - assertTrue(view.getAllJobs().isEmpty()); - scheduleMessage(60000, -1, -1); - assertFalse(view.getAllJobs().isEmpty()); - assertEquals(1, view.getAllJobs().size()); - scheduleMessage(60000, -1, -1); - assertEquals(2, view.getAllJobs().size()); - } - - @Test - public void testRemvoeJob() throws Exception { - JobSchedulerViewMBean view = getJobSchedulerMBean(); - assertNotNull(view); - assertTrue(view.getAllJobs().isEmpty()); - scheduleMessage(60000, -1, -1); - assertFalse(view.getAllJobs().isEmpty()); - TabularData jobs = view.getAllJobs(); - assertEquals(1, jobs.size()); - for (Object key : jobs.keySet()) { - String jobId = ((List) key).get(0).toString(); - LOG.info("Attempting to remove Job: {}", jobId); - view.removeJob(jobId); - } - assertTrue(view.getAllJobs().isEmpty()); - } - - @Test - public void testRemvoeJobInRange() throws Exception { - JobSchedulerViewMBean view = getJobSchedulerMBean(); - assertNotNull(view); - assertTrue(view.getAllJobs().isEmpty()); - scheduleMessage(60000, -1, -1); - assertFalse(view.getAllJobs().isEmpty()); - String now = JobSupport.getDateTime(System.currentTimeMillis()); - String later = JobSupport.getDateTime(System.currentTimeMillis() + 120 * 1000); - view.removeAllJobs(now, later); - assertTrue(view.getAllJobs().isEmpty()); - } - - @Test - public void testGetNextScheduledJob() throws Exception { - JobSchedulerViewMBean view = getJobSchedulerMBean(); - assertNotNull(view); - assertTrue(view.getAllJobs().isEmpty()); - scheduleMessage(60000, -1, -1); - assertFalse(view.getAllJobs().isEmpty()); - long before = System.currentTimeMillis() + 57 * 1000; - long toLate = System.currentTimeMillis() + 63 * 1000; - String next = view.getNextScheduleTime(); - long nextTime = JobSupport.getDataTime(next); - LOG.info("Next Scheduled Time: {} should be after: {}", next, JobSupport.getDateTime(before)); - assertTrue(nextTime > before); - assertTrue(nextTime < toLate); - } - - @Test - public void testGetExecutionCount() throws Exception { - final JobSchedulerViewMBean view = getJobSchedulerMBean(); - assertNotNull(view); - assertTrue(view.getAllJobs().isEmpty()); - scheduleMessage(10000, 1000, 10); - assertFalse(view.getAllJobs().isEmpty()); - TabularData jobs = view.getAllJobs(); - assertEquals(1, jobs.size()); - String jobId = null; - for (Object key : jobs.keySet()) { - jobId = ((List) key).get(0).toString(); - } - - final String fixedJobId = jobId; - LOG.info("Attempting to get execution count for Job: {}", jobId); - assertEquals(0, view.getExecutionCount(jobId)); - - assertTrue("Should execute again", Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - return view.getExecutionCount(fixedJobId) > 0; - } - })); - } - - @Override - protected boolean isUseJmx() { - return true; - } - - protected void scheduleMessage(int time, int period, int repeat) throws Exception { - Connection connection = createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage("test msg"); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, period); - message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, repeat); - producer.send(message); - connection.close(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerManagementTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerManagementTest.java deleted file mode 100644 index 47efffa2a6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerManagementTest.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.activemq.broker.scheduler; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ScheduledMessage; -import org.apache.activemq.util.IdGenerator; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - -public class JobSchedulerManagementTest extends JobSchedulerTestSupport { - - private static final transient Logger LOG = LoggerFactory.getLogger(JobSchedulerManagementTest.class); - - @Test - public void testRemoveAllScheduled() throws Exception { - final int COUNT = 5; - Connection connection = createConnection(); - - // Setup the scheduled Message - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(6), COUNT); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // Create the Browse Destination and the Reply To location - Destination management = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION); - - // Create the eventual Consumer to receive the scheduled message - MessageConsumer consumer = session.createConsumer(destination); - - final CountDownLatch latch = new CountDownLatch(COUNT); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - } - }); - - connection.start(); - - // Send the remove request - MessageProducer producer = session.createProducer(management); - Message request = session.createMessage(); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_REMOVEALL); - producer.send(request); - - // Now wait and see if any get delivered, none should. - latch.await(10, TimeUnit.SECONDS); - assertEquals(latch.getCount(), COUNT); - } - - @Test - public void testRemoveAllScheduledAtTime() throws Exception { - final int COUNT = 3; - Connection connection = createConnection(); - - // Setup the scheduled Message - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(6)); - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(15)); - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(20)); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // Create the Browse Destination and the Reply To location - Destination management = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION); - Destination browseDest = session.createTemporaryQueue(); - - // Create the eventual Consumer to receive the scheduled message - MessageConsumer consumer = session.createConsumer(destination); - - final CountDownLatch latch = new CountDownLatch(COUNT); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - } - }); - - // Create the "Browser" - MessageConsumer browser = session.createConsumer(browseDest); - final CountDownLatch browsedLatch = new CountDownLatch(COUNT); - browser.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - browsedLatch.countDown(); - LOG.debug("Scheduled Message Browser got Message: " + message); - } - }); - - connection.start(); - - long start = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(10); - long end = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(30); - - // Send the remove request - MessageProducer producer = session.createProducer(management); - Message request = session.createMessage(); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_REMOVEALL); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION_START_TIME, Long.toString(start)); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION_END_TIME, Long.toString(end)); - producer.send(request); - - // Send the browse request - request = session.createMessage(); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_BROWSE); - request.setJMSReplyTo(browseDest); - producer.send(request); - - // now see if we got back only the one remaining message. - latch.await(10, TimeUnit.SECONDS); - assertEquals(2, browsedLatch.getCount()); - - // Now wait and see if any get delivered, none should. - latch.await(10, TimeUnit.SECONDS); - assertEquals(2, latch.getCount()); - } - - @Test - public void testBrowseAllScheduled() throws Exception { - final int COUNT = 10; - Connection connection = createConnection(); - - // Setup the scheduled Message - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(9), COUNT); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // Create the Browse Destination and the Reply To location - Destination requestBrowse = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION); - Destination browseDest = session.createTemporaryQueue(); - - // Create the eventual Consumer to receive the scheduled message - MessageConsumer consumer = session.createConsumer(destination); - - final CountDownLatch latch = new CountDownLatch(COUNT); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - } - }); - - // Create the "Browser" - MessageConsumer browser = session.createConsumer(browseDest); - final CountDownLatch browsedLatch = new CountDownLatch(COUNT); - browser.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - browsedLatch.countDown(); - LOG.debug("Scheduled Message Browser got Message: " + message); - } - }); - - connection.start(); - - // Send the browse request - MessageProducer producer = session.createProducer(requestBrowse); - Message request = session.createMessage(); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_BROWSE); - request.setJMSReplyTo(browseDest); - producer.send(request); - - // make sure the message isn't delivered early because we browsed it - Thread.sleep(2000); - assertEquals(latch.getCount(), COUNT); - - // now see if we got all the scheduled messages on the browse - // destination. - latch.await(10, TimeUnit.SECONDS); - assertEquals(browsedLatch.getCount(), 0); - - // now check that they all got delivered - latch.await(10, TimeUnit.SECONDS); - assertEquals(latch.getCount(), 0); - } - - @Test - public void testBrowseWindowlScheduled() throws Exception { - final int COUNT = 10; - Connection connection = createConnection(); - - // Setup the scheduled Message - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(5)); - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(10), COUNT); - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(20)); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // Create the Browse Destination and the Reply To location - Destination requestBrowse = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION); - Destination browseDest = session.createTemporaryQueue(); - - // Create the eventual Consumer to receive the scheduled message - MessageConsumer consumer = session.createConsumer(destination); - - final CountDownLatch latch = new CountDownLatch(COUNT + 2); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - } - }); - - // Create the "Browser" - MessageConsumer browser = session.createConsumer(browseDest); - final CountDownLatch browsedLatch = new CountDownLatch(COUNT); - browser.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - browsedLatch.countDown(); - LOG.debug("Scheduled Message Browser got Message: " + message); - } - }); - - connection.start(); - - long start = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(6); - long end = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(15); - - // Send the browse request - MessageProducer producer = session.createProducer(requestBrowse); - Message request = session.createMessage(); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_BROWSE); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION_START_TIME, Long.toString(start)); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION_END_TIME, Long.toString(end)); - request.setJMSReplyTo(browseDest); - producer.send(request); - - // make sure the message isn't delivered early because we browsed it - Thread.sleep(2000); - assertEquals(COUNT + 2, latch.getCount()); - - // now see if we got all the scheduled messages on the browse - // destination. - latch.await(15, TimeUnit.SECONDS); - assertEquals(0, browsedLatch.getCount()); - - // now see if we got all the scheduled messages on the browse - // destination. - latch.await(20, TimeUnit.SECONDS); - assertEquals(0, latch.getCount()); - } - - @Test - public void testRemoveScheduled() throws Exception { - final int COUNT = 10; - Connection connection = createConnection(); - - // Setup the scheduled Message - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(9), COUNT); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // Create the Browse Destination and the Reply To location - Destination management = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION); - Destination browseDest = session.createTemporaryQueue(); - - // Create the eventual Consumer to receive the scheduled message - MessageConsumer consumer = session.createConsumer(destination); - MessageProducer producer = session.createProducer(management); - - final CountDownLatch latch = new CountDownLatch(COUNT); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - } - }); - - // Create the "Browser" - Session browseSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer browser = browseSession.createConsumer(browseDest); - - connection.start(); - - // Send the browse request - Message request = session.createMessage(); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_BROWSE); - request.setJMSReplyTo(browseDest); - producer.send(request); - - // Browse all the Scheduled Messages. - for (int i = 0; i < COUNT; ++i) { - Message message = browser.receive(2000); - assertNotNull(message); - - try { - Message remove = session.createMessage(); - remove.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_REMOVE); - remove.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_ID, message.getStringProperty(ScheduledMessage.AMQ_SCHEDULED_ID)); - producer.send(remove); - } catch (Exception e) { - } - } - - // now check that they all got removed and are not delivered. - latch.await(11, TimeUnit.SECONDS); - assertEquals(COUNT, latch.getCount()); - } - - @Test - public void testRemoveNotScheduled() throws Exception { - Connection connection = createConnection(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // Create the Browse Destination and the Reply To location - Destination management = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION); - - MessageProducer producer = session.createProducer(management); - - try { - - // Send the remove request - Message remove = session.createMessage(); - remove.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_REMOVEALL); - remove.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_ID, new IdGenerator().generateId()); - producer.send(remove); - } catch (Exception e) { - fail("Caught unexpected exception during remove of unscheduled message."); - } - } - - @Test - public void testBrowseWithSelector() throws Exception { - Connection connection = createConnection(); - - // Setup the scheduled Message - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(9)); - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(10)); - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(5)); - scheduleMessage(connection, TimeUnit.SECONDS.toMillis(45)); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // Create the Browse Destination and the Reply To location - Destination requestBrowse = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION); - Destination browseDest = session.createTemporaryTopic(); - - // Create the "Browser" - MessageConsumer browser = session.createConsumer(browseDest, ScheduledMessage.AMQ_SCHEDULED_DELAY + " = 45000"); - - connection.start(); - - // Send the browse request - MessageProducer producer = session.createProducer(requestBrowse); - Message request = session.createMessage(); - request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_BROWSE); - request.setJMSReplyTo(browseDest); - producer.send(request); - - // Now try and receive the one we selected - Message message = browser.receive(5000); - assertNotNull(message); - assertEquals(45000, message.getLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY)); - - // Now check if there are anymore, there shouldn't be - message = browser.receive(5000); - assertNull(message); - } - - protected void scheduleMessage(Connection connection, long delay) throws Exception { - scheduleMessage(connection, delay, 1); - } - - protected void scheduleMessage(Connection connection, long delay, int count) throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage("test msg"); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay); - - for (int i = 0; i < count; ++i) { - producer.send(message); - } - - producer.close(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerStoreCheckpointTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerStoreCheckpointTest.java deleted file mode 100644 index 0f45259ab6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerStoreCheckpointTest.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.broker.scheduler; - -import java.io.File; -import java.io.IOException; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.store.kahadb.scheduler.JobSchedulerStoreImpl; -import org.apache.activemq.util.ByteSequence; -import org.apache.activemq.util.IOHelper; -import org.apache.activemq.util.Wait; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class JobSchedulerStoreCheckpointTest { - - static final Logger LOG = LoggerFactory.getLogger(JobSchedulerStoreCheckpointTest.class); - - private JobSchedulerStoreImpl store; - private JobScheduler scheduler; - private ByteSequence payload; - - @Before - public void setUp() throws Exception { - File directory = new File("target/test/ScheduledJobsDB"); - IOHelper.mkdirs(directory); - IOHelper.deleteChildren(directory); - startStore(directory); - - byte[] data = new byte[8192]; - for (int i = 0; i < data.length; ++i) { - data[i] = (byte) (i % 256); - } - - payload = new ByteSequence(data); - } - - protected void startStore(File directory) throws Exception { - store = new JobSchedulerStoreImpl(); - store.setDirectory(directory); - store.setCheckpointInterval(5000); - store.setCleanupInterval(10000); - store.setJournalMaxFileLength(10 * 1024); - store.start(); - scheduler = store.getJobScheduler("test"); - scheduler.startDispatching(); - } - - private int getNumJournalFiles() throws IOException { - return store.getJournal().getFileMap().size(); - } - - @After - public void tearDown() throws Exception { - scheduler.stopDispatching(); - store.stop(); - } - - @Test - public void test() throws Exception { - final int COUNT = 10; - final CountDownLatch latch = new CountDownLatch(COUNT); - scheduler.addListener(new JobListener() { - @Override - public void scheduledJob(String id, ByteSequence job) { - latch.countDown(); - } - }); - - long time = TimeUnit.SECONDS.toMillis(30); - for (int i = 0; i < COUNT; i++) { - scheduler.schedule("id" + i, payload, "", time, 0, 0); - } - - int size = scheduler.getAllJobs().size(); - assertEquals(size, COUNT); - - LOG.info("Number of journal log files: {}", getNumJournalFiles()); - // need a little slack so go over 60 seconds - assertTrue(latch.await(70, TimeUnit.SECONDS)); - assertEquals(0, latch.getCount()); - - for (int i = 0; i < COUNT; i++) { - scheduler.schedule("id" + i, payload, "", time, 0, 0); - } - - LOG.info("Number of journal log files: {}", getNumJournalFiles()); - // need a little slack so go over 60 seconds - assertTrue(latch.await(70, TimeUnit.SECONDS)); - assertEquals(0, latch.getCount()); - - assertTrue("Should be only one log left: " + getNumJournalFiles(), Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - return getNumJournalFiles() == 1; - } - }, TimeUnit.MINUTES.toMillis(2))); - - LOG.info("Number of journal log files: {}", getNumJournalFiles()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerStoreTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerStoreTest.java deleted file mode 100644 index c278da5f57..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerStoreTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.scheduler; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import org.apache.activemq.store.kahadb.scheduler.JobSchedulerStoreImpl; -import org.apache.activemq.util.ByteSequence; -import org.apache.activemq.util.IOHelper; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; - -public class JobSchedulerStoreTest { - - private static final Logger LOG = LoggerFactory.getLogger(JobSchedulerStoreTest.class); - - @Test(timeout = 120 * 1000) - public void testRestart() throws Exception { - JobSchedulerStore store = new JobSchedulerStoreImpl(); - File directory = new File("target/test/ScheduledDB"); - IOHelper.mkdirs(directory); - IOHelper.deleteChildren(directory); - store.setDirectory(directory); - final int NUMBER = 1000; - store.start(); - List list = new ArrayList<>(); - for (int i = 0; i < NUMBER; i++) { - ByteSequence buff = new ByteSequence(new String("testjob" + i).getBytes()); - list.add(buff); - } - - JobScheduler js = store.getJobScheduler("test"); - js.startDispatching(); - int count = 0; - long startTime = 10 * 60 * 1000; - long period = startTime; - for (ByteSequence job : list) { - js.schedule("id:" + (count++), job, "", startTime, period, -1); - } - - List test = js.getAllJobs(); - LOG.debug("Found {} jobs in the store before restart", test.size()); - assertEquals(list.size(), test.size()); - store.stop(); - - store.start(); - js = store.getJobScheduler("test"); - test = js.getAllJobs(); - LOG.debug("Found {} jobs in the store after restart", test.size()); - assertEquals(list.size(), test.size()); - - for (int i = 0; i < list.size(); i++) { - String orig = new String(list.get(i).getData()); - String payload = new String(test.get(i).getPayload()); - assertEquals(orig, payload); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTest.java deleted file mode 100644 index e3f700f762..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTest.java +++ /dev/null @@ -1,297 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.scheduler; - -import java.io.File; -import java.util.Calendar; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.store.kahadb.scheduler.JobSchedulerStoreImpl; -import org.apache.activemq.util.ByteSequence; -import org.apache.activemq.util.IOHelper; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class JobSchedulerTest { - - private static final Logger LOG = LoggerFactory.getLogger(JobSchedulerTest.class); - - private JobSchedulerStore store; - private JobScheduler scheduler; - - @Test - public void testAddLongStringByteSequence() throws Exception { - final int COUNT = 10; - final CountDownLatch latch = new CountDownLatch(COUNT); - scheduler.addListener(new JobListener() { - @Override - public void scheduledJob(String id, ByteSequence job) { - latch.countDown(); - } - - }); - for (int i = 0; i < COUNT; i++) { - String test = new String("test" + i); - scheduler.schedule("id" + i, new ByteSequence(test.getBytes()), 1000); - } - latch.await(5, TimeUnit.SECONDS); - assertEquals(0, latch.getCount()); - } - - @Test - public void testAddCronAndByteSequence() throws Exception { - - final CountDownLatch latch = new CountDownLatch(1); - scheduler.addListener(new JobListener() { - @Override - public void scheduledJob(String id, ByteSequence job) { - latch.countDown(); - } - }); - - Calendar current = Calendar.getInstance(); - current.add(Calendar.MINUTE, 1); - int minutes = current.get(Calendar.MINUTE); - int hour = current.get(Calendar.HOUR_OF_DAY); - int day = current.get(Calendar.DAY_OF_WEEK) - 1; - - String cronTab = String.format("%d %d * * %d", minutes, hour, day); - - String str = new String("test1"); - scheduler.schedule("id:1", new ByteSequence(str.getBytes()), cronTab, 0, 0, 0); - - // need a little slack so go over 60 seconds - assertTrue(latch.await(70, TimeUnit.SECONDS)); - assertEquals(0, latch.getCount()); - } - - @Test - public void testAddLongLongIntStringByteSequence() throws Exception { - final int COUNT = 10; - final CountDownLatch latch = new CountDownLatch(COUNT); - scheduler.addListener(new JobListener() { - @Override - public void scheduledJob(String id, ByteSequence job) { - latch.countDown(); - } - }); - long time = 2000; - for (int i = 0; i < COUNT; i++) { - String test = new String("test" + i); - scheduler.schedule("id" + i, new ByteSequence(test.getBytes()), "", time, 10, -1); - } - assertTrue(latch.getCount() == COUNT); - latch.await(3000, TimeUnit.SECONDS); - assertTrue(latch.getCount() == 0); - } - - @Test - public void testAddStopThenDeliver() throws Exception { - final int COUNT = 10; - final CountDownLatch latch = new CountDownLatch(COUNT); - long time = 2000; - for (int i = 0; i < COUNT; i++) { - String test = new String("test" + i); - scheduler.schedule("id" + i, new ByteSequence(test.getBytes()), "", time, 1000, -1); - } - File directory = store.getDirectory(); - tearDown(); - startStore(directory); - scheduler.addListener(new JobListener() { - @Override - public void scheduledJob(String id, ByteSequence job) { - latch.countDown(); - } - }); - assertTrue(latch.getCount() == COUNT); - latch.await(3000, TimeUnit.SECONDS); - assertTrue(latch.getCount() == 0); - } - - @Test - public void testRemoveLong() throws Exception { - final int COUNT = 10; - - long time = 60000; - for (int i = 0; i < COUNT; i++) { - String str = new String("test" + i); - scheduler.schedule("id" + i, new ByteSequence(str.getBytes()), "", time, 1000, -1); - } - - int size = scheduler.getAllJobs().size(); - assertEquals(size, COUNT); - - long removeTime = scheduler.getNextScheduleTime(); - scheduler.remove(removeTime); - - // If all jobs are not started within the same second we need to call remove again - if (size != 0) { - removeTime = scheduler.getNextScheduleTime(); - scheduler.remove(removeTime); - } - - size = scheduler.getAllJobs().size(); - assertEquals(0, size); - } - - @Test - public void testRemoveString() throws Exception { - final int COUNT = 10; - final String test = "TESTREMOVE"; - long time = 20000; - - for (int i = 0; i < COUNT; i++) { - String str = new String("test" + i); - scheduler.schedule("id" + i, new ByteSequence(str.getBytes()), "", time, 1000, -1); - if (i == COUNT / 2) { - scheduler.schedule(test, new ByteSequence(test.getBytes()), "", time, 1000, -1); - } - } - - int size = scheduler.getAllJobs().size(); - assertEquals(size, COUNT + 1); - scheduler.remove(test); - size = scheduler.getAllJobs().size(); - assertEquals(size, COUNT); - } - - @Test - public void testGetExecutionCount() throws Exception { - final String jobId = "Job-1"; - long time = 10000; - final CountDownLatch done = new CountDownLatch(10); - - String str = new String("test"); - scheduler.schedule(jobId, new ByteSequence(str.getBytes()), "", time, 1000, 10); - - int size = scheduler.getAllJobs().size(); - assertEquals(size, 1); - - scheduler.addListener(new JobListener() { - @Override - public void scheduledJob(String id, ByteSequence job) { - LOG.info("Job executed: {}", 11 - done.getCount()); - done.countDown(); - } - }); - - List jobs = scheduler.getNextScheduleJobs(); - assertEquals(1, jobs.size()); - Job job = jobs.get(0); - assertEquals(jobId, job.getJobId()); - assertEquals(0, job.getExecutionCount()); - assertTrue("Should have fired ten times.", done.await(60, TimeUnit.SECONDS)); - // The job is not updated on the last firing as it is removed from the store following - // it's last execution so the count will always be one less than the max firings. - assertTrue(job.getExecutionCount() >= 9); - } - - @Test - public void testgetAllJobs() throws Exception { - final int COUNT = 10; - final String ID = "id:"; - long time = 20000; - - for (int i = 0; i < COUNT; i++) { - String str = new String("test" + i); - scheduler.schedule(ID + i, new ByteSequence(str.getBytes()), "", time, 10 + i, -1); - } - - List list = scheduler.getAllJobs(); - - assertEquals(list.size(), COUNT); - int count = 0; - for (Job job : list) { - assertEquals(job.getJobId(), ID + count); - count++; - } - } - - @Test - public void testgetAllJobsInRange() throws Exception { - final int COUNT = 10; - final String ID = "id:"; - long start = 10000; - - for (int i = 0; i < COUNT; i++) { - String str = new String("test" + i); - scheduler.schedule(ID + i, new ByteSequence(str.getBytes()), "", start + (i * 1000), 10000 + i, 0); - } - - start = System.currentTimeMillis(); - long finish = start + 12000 + (COUNT * 1000); - List list = scheduler.getAllJobs(start, finish); - - assertEquals(COUNT, list.size()); - int count = 0; - for (Job job : list) { - assertEquals(job.getJobId(), ID + count); - count++; - } - } - - @Test - public void testRemoveAllJobsInRange() throws Exception { - final int COUNT = 10; - final String ID = "id:"; - long start = 10000; - - for (int i = 0; i < COUNT; i++) { - String str = new String("test" + i); - scheduler.schedule(ID + i, new ByteSequence(str.getBytes()), "", start + (i * 1000), 10000 + i, 0); - } - start = System.currentTimeMillis(); - long finish = start + 12000 + (COUNT * 1000); - scheduler.removeAllJobs(start, finish); - - assertTrue(scheduler.getAllJobs().isEmpty()); - } - - @Before - public void setUp() throws Exception { - File directory = new File("target/test/ScheduledJobsDB"); - IOHelper.mkdirs(directory); - IOHelper.deleteChildren(directory); - startStore(directory); - } - - protected JobSchedulerStore createJobSchedulerStore() throws Exception { - return new JobSchedulerStoreImpl(); - } - - protected void startStore(File directory) throws Exception { - store = createJobSchedulerStore(); - store.setDirectory(directory); - store.start(); - scheduler = store.getJobScheduler("test"); - scheduler.startDispatching(); - } - - @After - public void tearDown() throws Exception { - scheduler.stopDispatching(); - store.stop(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTestSupport.java deleted file mode 100644 index 07d81e5587..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTestSupport.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.activemq.broker.scheduler; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.Queue; -import javax.management.ObjectName; -import java.io.File; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.jmx.JobSchedulerViewMBean; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.util.IOHelper; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.rules.TestName; - -/** - * Base class for tests of the Broker's JobSchedulerStore. - */ -public class JobSchedulerTestSupport { - - @Rule - public TestName name = new TestName(); - - protected String connectionUri; - protected BrokerService broker; - protected JobScheduler jobScheduler; - protected Queue destination; - - @Before - public void setUp() throws Exception { - connectionUri = "vm://localhost"; - destination = new ActiveMQQueue(name.getMethodName()); - - broker = createBroker(); - broker.start(); - broker.waitUntilStarted(); - - jobScheduler = broker.getJobSchedulerStore().getJobScheduler("JMS"); - } - - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } - - protected Connection createConnection() throws Exception { - return createConnectionFactory().createConnection(); - } - - protected ConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(connectionUri); - } - - protected BrokerService createBroker() throws Exception { - return createBroker(true); - } - - protected boolean isUseJmx() { - return false; - } - - protected boolean isPersistent() { - return true; - } - - protected JobSchedulerViewMBean getJobSchedulerMBean() throws Exception { - ObjectName objectName = broker.getAdminView().getJMSJobScheduler(); - JobSchedulerViewMBean scheduler = null; - if (objectName != null) { - scheduler = (JobSchedulerViewMBean) broker.getManagementContext().newProxyInstance(objectName, JobSchedulerViewMBean.class, true); - } - - return scheduler; - } - - protected BrokerService createBroker(boolean delete) throws Exception { - File schedulerDirectory = new File("target/scheduler"); - if (delete) { - IOHelper.mkdirs(schedulerDirectory); - IOHelper.deleteChildren(schedulerDirectory); - } - - BrokerService answer = new BrokerService(); - answer.setPersistent(isPersistent()); - answer.setDeleteAllMessagesOnStartup(true); - answer.setDataDirectory("target"); - answer.setSchedulerDirectoryFile(schedulerDirectory); - answer.setSchedulerSupport(true); - answer.setUseJmx(isUseJmx()); - return answer; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTxTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTxTest.java deleted file mode 100644 index 578ded802d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/JobSchedulerTxTest.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.activemq.broker.scheduler; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ScheduledMessage; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class JobSchedulerTxTest extends JobSchedulerTestSupport { - - @Test - public void testTxSendWithRollback() throws Exception { - final int COUNT = 10; - Connection connection = createConnection(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - final CountDownLatch latch = new CountDownLatch(COUNT); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - } - }); - - connection.start(); - long time = 5000; - Session producerSession = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageProducer producer = producerSession.createProducer(destination); - - for (int i = 0; i < COUNT; ++i) { - TextMessage message = session.createTextMessage("test msg"); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - producer.send(message); - } - producer.close(); - producerSession.rollback(); - - // make sure the message isn't delivered early - Thread.sleep(2000); - assertEquals(COUNT, latch.getCount()); - latch.await(5, TimeUnit.SECONDS); - assertEquals(COUNT, latch.getCount()); - } - - @Test - public void testTxSendWithCommit() throws Exception { - final int COUNT = 10; - Connection connection = createConnection(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - final CountDownLatch latch = new CountDownLatch(COUNT); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - } - }); - - connection.start(); - long time = 5000; - Session producerSession = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageProducer producer = producerSession.createProducer(destination); - - for (int i = 0; i < COUNT; ++i) { - TextMessage message = session.createTextMessage("test msg"); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - producer.send(message); - } - producer.close(); - producerSession.commit(); - - // make sure the message isn't delivered early - Thread.sleep(2000); - assertEquals(COUNT, latch.getCount()); - latch.await(5, TimeUnit.SECONDS); - assertEquals(0, latch.getCount()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/KahaDBSchedulerIndexRebuildTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/KahaDBSchedulerIndexRebuildTest.java deleted file mode 100644 index 31c460bb63..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/KahaDBSchedulerIndexRebuildTest.java +++ /dev/null @@ -1,195 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.scheduler; - -import javax.jms.Connection; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.io.File; -import java.io.IOException; -import java.security.ProtectionDomain; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ScheduledMessage; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.store.kahadb.scheduler.JobSchedulerStoreImpl; -import org.apache.activemq.util.IOHelper; -import org.apache.activemq.util.Wait; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -public class KahaDBSchedulerIndexRebuildTest { - - static final Logger LOG = LoggerFactory.getLogger(KahaDBSchedulerIndexRebuildTest.class); - - private BrokerService broker = null; - private final int NUM_JOBS = 50; - - static String basedir; - - static { - try { - ProtectionDomain protectionDomain = SchedulerDBVersionTest.class.getProtectionDomain(); - basedir = new File(new File(protectionDomain.getCodeSource().getLocation().getPath()), "../.").getCanonicalPath(); - } catch (IOException e) { - basedir = "."; - } - } - - private final File schedulerStoreDir = new File(basedir, "activemq-data/store/scheduler"); - private final File storeDir = new File(basedir, "activemq-data/store/"); - - @Before - public void setUp() throws Exception { - LOG.info("Test Dir = {}", schedulerStoreDir); - } - - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - } - } - - @Test - public void testIndexRebuilds() throws Exception { - IOHelper.deleteFile(schedulerStoreDir); - - JobSchedulerStoreImpl schedulerStore = createScheduler(); - broker = createBroker(schedulerStore); - broker.start(); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = cf.createConnection(); - connection.start(); - for (int i = 0; i < NUM_JOBS; ++i) { - scheduleRepeating(connection); - } - connection.close(); - - JobScheduler scheduler = schedulerStore.getJobScheduler("JMS"); - assertNotNull(scheduler); - assertEquals(NUM_JOBS, scheduler.getAllJobs().size()); - - broker.stop(); - - IOHelper.delete(new File(schedulerStoreDir, "scheduleDB.data")); - - schedulerStore = createScheduler(); - broker = createBroker(schedulerStore); - broker.start(); - - scheduler = schedulerStore.getJobScheduler("JMS"); - assertNotNull(scheduler); - assertEquals(NUM_JOBS, scheduler.getAllJobs().size()); - } - - @Test - public void testIndexRebuildsAfterSomeJobsExpire() throws Exception { - IOHelper.deleteFile(schedulerStoreDir); - - JobSchedulerStoreImpl schedulerStore = createScheduler(); - broker = createBroker(schedulerStore); - broker.start(); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = cf.createConnection(); - connection.start(); - for (int i = 0; i < NUM_JOBS; ++i) { - scheduleRepeating(connection); - scheduleOneShot(connection); - } - connection.close(); - - JobScheduler scheduler = schedulerStore.getJobScheduler("JMS"); - assertNotNull(scheduler); - assertEquals(NUM_JOBS * 2, scheduler.getAllJobs().size()); - - final JobScheduler awaitingOneShotTimeout = scheduler; - assertTrue("One shot jobs should time out", Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - return awaitingOneShotTimeout.getAllJobs().size() == NUM_JOBS; - } - }, TimeUnit.MINUTES.toMillis(2))); - - broker.stop(); - - IOHelper.delete(new File(schedulerStoreDir, "scheduleDB.data")); - - schedulerStore = createScheduler(); - broker = createBroker(schedulerStore); - broker.start(); - - scheduler = schedulerStore.getJobScheduler("JMS"); - assertNotNull(scheduler); - assertEquals(NUM_JOBS, scheduler.getAllJobs().size()); - } - - private void scheduleRepeating(Connection connection) throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createQueue("test.queue"); - MessageProducer producer = session.createProducer(queue); - - TextMessage message = session.createTextMessage("test msg"); - long time = 360 * 1000; - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 500); - message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, -1); - producer.send(message); - producer.close(); - } - - private void scheduleOneShot(Connection connection) throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createQueue("test.queue"); - MessageProducer producer = session.createProducer(queue); - - TextMessage message = session.createTextMessage("test msg"); - long time = TimeUnit.SECONDS.toMillis(30); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, 0); - producer.send(message); - producer.close(); - } - - protected JobSchedulerStoreImpl createScheduler() { - JobSchedulerStoreImpl scheduler = new JobSchedulerStoreImpl(); - scheduler.setDirectory(schedulerStoreDir); - scheduler.setJournalMaxFileLength(10 * 1024); - return scheduler; - } - - protected BrokerService createBroker(JobSchedulerStoreImpl scheduler) throws Exception { - BrokerService answer = new BrokerService(); - answer.setJobSchedulerStore(scheduler); - answer.setPersistent(true); - answer.setDataDirectory(storeDir.getAbsolutePath()); - answer.setSchedulerSupport(true); - answer.setUseJmx(false); - return answer; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/KahaDBSchedulerMissingJournalLogsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/KahaDBSchedulerMissingJournalLogsTest.java deleted file mode 100644 index ebfa3eed0d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/KahaDBSchedulerMissingJournalLogsTest.java +++ /dev/null @@ -1,204 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.broker.scheduler; - -import javax.jms.Connection; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.io.File; -import java.io.IOException; -import java.security.ProtectionDomain; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ScheduledMessage; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.store.kahadb.disk.journal.DataFile; -import org.apache.activemq.store.kahadb.scheduler.JobSchedulerStoreImpl; -import org.apache.activemq.util.IOHelper; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -/** - * Test that the store recovers even if some log files are missing. - */ -public class KahaDBSchedulerMissingJournalLogsTest { - - static final Logger LOG = LoggerFactory.getLogger(KahaDBSchedulerIndexRebuildTest.class); - - private BrokerService broker = null; - private JobSchedulerStoreImpl schedulerStore = null; - - private final int NUM_LOGS = 6; - - static String basedir; - - static { - try { - ProtectionDomain protectionDomain = SchedulerDBVersionTest.class.getProtectionDomain(); - basedir = new File(new File(protectionDomain.getCodeSource().getLocation().getPath()), "../.").getCanonicalPath(); - } catch (IOException e) { - basedir = "."; - } - } - - private final File schedulerStoreDir = new File(basedir, "activemq-data/store/scheduler"); - private final File storeDir = new File(basedir, "activemq-data/store/"); - - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - IOHelper.deleteFile(schedulerStoreDir); - LOG.info("Test Dir = {}", schedulerStoreDir); - - createBroker(); - broker.start(); - broker.waitUntilStarted(); - - schedulerStore = (JobSchedulerStoreImpl) broker.getJobSchedulerStore(); - } - - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } - - @Test(timeout = 120 * 1000) - public void testMissingLogsCausesBrokerToFail() throws Exception { - fillUpSomeLogFiles(); - - int jobCount = schedulerStore.getJobScheduler("JMS").getAllJobs().size(); - LOG.info("There are {} jobs in the store.", jobCount); - - List toDelete = new ArrayList<>(); - Map files = schedulerStore.getJournal().getFileMap(); - for (int i = files.size(); i > files.size() / 2; i--) { - toDelete.add(files.get(i).getFile()); - } - - broker.stop(); - broker.waitUntilStopped(); - - for (File file : toDelete) { - LOG.info("File to delete: {}", file); - IOHelper.delete(file); - } - - try { - createBroker(); - fail("Should not start when logs are missing."); - } catch (Exception e) { - } - } - - @Test(timeout = 120 * 1000) - public void testRecoverWhenSomeLogsAreMissing() throws Exception { - fillUpSomeLogFiles(); - - int jobCount = schedulerStore.getJobScheduler("JMS").getAllJobs().size(); - LOG.info("There are {} jobs in the store.", jobCount); - - List toDelete = new ArrayList<>(); - Map files = schedulerStore.getJournal().getFileMap(); - for (int i = files.size() - 1; i > files.size() / 2; i--) { - toDelete.add(files.get(i).getFile()); - } - - broker.stop(); - broker.waitUntilStopped(); - - for (File file : toDelete) { - LOG.info("File to delete: {}", file); - IOHelper.delete(file); - } - - schedulerStore = createScheduler(); - schedulerStore.setIgnoreMissingJournalfiles(true); - - createBroker(schedulerStore); - broker.start(); - broker.waitUntilStarted(); - - int postRecoverJobCount = schedulerStore.getJobScheduler("JMS").getAllJobs().size(); - assertTrue(postRecoverJobCount > 0); - assertTrue(postRecoverJobCount < jobCount); - } - - private void fillUpSomeLogFiles() throws Exception { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = cf.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createQueue("test.queue"); - MessageProducer producer = session.createProducer(queue); - connection.start(); - while (true) { - scheduleRepeating(session, producer); - if (schedulerStore.getJournal().getFileMap().size() == NUM_LOGS) { - break; - } - } - connection.close(); - } - - private void scheduleRepeating(Session session, MessageProducer producer) throws Exception { - TextMessage message = session.createTextMessage("test msg"); - long time = 360 * 1000; - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 500); - message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, -1); - producer.send(message); - } - - protected JobSchedulerStoreImpl createScheduler() { - JobSchedulerStoreImpl scheduler = new JobSchedulerStoreImpl(); - scheduler.setDirectory(schedulerStoreDir); - scheduler.setJournalMaxFileLength(10 * 1024); - return scheduler; - } - - protected void createBroker() throws Exception { - createBroker(createScheduler()); - } - - protected void createBroker(JobSchedulerStoreImpl scheduler) throws Exception { - broker = new BrokerService(); - broker.setJobSchedulerStore(scheduler); - broker.setPersistent(true); - broker.setDataDirectory(storeDir.getAbsolutePath()); - broker.setSchedulerSupport(true); - broker.setUseJmx(false); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/LostScheduledMessagesTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/LostScheduledMessagesTest.java deleted file mode 100644 index 180cb050b4..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/LostScheduledMessagesTest.java +++ /dev/null @@ -1,152 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.broker.scheduler; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.io.File; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ScheduledMessage; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.util.IOHelper; -import org.apache.log4j.BasicConfigurator; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class LostScheduledMessagesTest { - - private BrokerService broker; - - private static final File schedulerDirectory = new File("target/test/ScheduledDB"); - private static final File messageDirectory = new File("target/test/MessageDB"); - private static final String QUEUE_NAME = "test"; - - @Before - public void setup() throws Exception { - IOHelper.mkdirs(schedulerDirectory); - IOHelper.deleteChildren(schedulerDirectory); - - IOHelper.mkdirs(messageDirectory); - IOHelper.deleteChildren(messageDirectory); - } - - private void startBroker() throws Exception { - broker = new BrokerService(); - broker.setSchedulerSupport(true); - broker.setPersistent(true); - broker.setDeleteAllMessagesOnStartup(false); - broker.setDataDirectory("target"); - broker.setSchedulerDirectoryFile(schedulerDirectory); - broker.setDataDirectoryFile(messageDirectory); - broker.setUseJmx(false); - broker.addConnector("vm://localhost"); - broker.start(); - } - - @After - public void tearDown() throws Exception { - broker.stop(); - BasicConfigurator.resetConfiguration(); - } - - @Test - public void MessagePassedNotUsingScheduling() throws Exception { - doTest(false); - } - - @Test - public void MessageLostWhenUsingScheduling() throws Exception { - doTest(true); - } - - private void doTest(boolean useScheduling) throws Exception { - - int DELIVERY_DELAY_MS = 5000; - - startBroker(); - - long startTime = System.currentTimeMillis(); - - // Send a message scheduled for delivery in 5 seconds - ConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = cf.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(session.createQueue(QUEUE_NAME)); - Message message = session.createTextMessage("test"); - if (useScheduling) { - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, DELIVERY_DELAY_MS); - } - producer.send(message); - - session.close(); - connection.close(); - - broker.getServices(); - - // shut down broker - broker.stop(); - broker.waitUntilStopped(); - - // Make sure that broker have stopped within delivery delay - long shutdownTime = System.currentTimeMillis(); - assertTrue("Failed to shut down broker in expected time. Test results inconclusive", shutdownTime - startTime < DELIVERY_DELAY_MS); - - // make sure that delivery falls into down time window - TimeUnit.MILLISECONDS.sleep(DELIVERY_DELAY_MS); - - // Start new broker instance - startBroker(); - - final AtomicLong receiveCounter = new AtomicLong(); - - cf = new ActiveMQConnectionFactory("vm://localhost"); - connection = cf.createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); - consumer.setMessageListener(new MessageListener() { - - @Override - public void onMessage(Message message) { - receiveCounter.incrementAndGet(); - } - }); - - // Wait for a while to let MQ process the message - TimeUnit.MILLISECONDS.sleep(DELIVERY_DELAY_MS * 2); - - session.close(); - connection.close(); - - assertEquals(1, receiveCounter.get()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/SchedulerDBVersionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/SchedulerDBVersionTest.java deleted file mode 100644 index fac55454e5..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/SchedulerDBVersionTest.java +++ /dev/null @@ -1,164 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.scheduler; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.io.File; -import java.io.IOException; -import java.security.ProtectionDomain; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ScheduledMessage; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.store.kahadb.scheduler.JobSchedulerStoreImpl; -import org.apache.activemq.util.IOHelper; -import org.junit.After; -import org.junit.Ignore; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; - -public class SchedulerDBVersionTest { - - static String basedir; - - static { - try { - ProtectionDomain protectionDomain = SchedulerDBVersionTest.class.getProtectionDomain(); - basedir = new File(new File(protectionDomain.getCodeSource().getLocation().getPath()), "../..").getCanonicalPath(); - } catch (IOException e) { - basedir = "."; - } - } - - static final Logger LOG = LoggerFactory.getLogger(SchedulerDBVersionTest.class); - final static File VERSION_LEGACY_JMS = new File(basedir + "/src/test/resources/org/apache/activemq/store/schedulerDB/legacy"); - - BrokerService broker = null; - - protected BrokerService createBroker(JobSchedulerStoreImpl scheduler) throws Exception { - BrokerService answer = new BrokerService(); - answer.setJobSchedulerStore(scheduler); - answer.setPersistent(true); - answer.setDataDirectory("target"); - answer.setSchedulerSupport(true); - answer.setUseJmx(false); - return answer; - } - - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - } - } - - @Ignore("Used only when a new version of the store needs to archive it's test data.") - @Test - public void testCreateStore() throws Exception { - JobSchedulerStoreImpl scheduler = new JobSchedulerStoreImpl(); - File dir = new File("src/test/resources/org/apache/activemq/store/schedulerDB/legacy"); - IOHelper.deleteFile(dir); - scheduler.setDirectory(dir); - scheduler.setJournalMaxFileLength(1024 * 1024); - broker = createBroker(scheduler); - broker.start(); - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = cf.createConnection(); - connection.start(); - scheduleRepeating(connection); - connection.close(); - broker.stop(); - } - - private void scheduleRepeating(Connection connection) throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createQueue("test.queue"); - MessageProducer producer = session.createProducer(queue); - - TextMessage message = session.createTextMessage("test msg"); - long time = 1000; - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, 500); - message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, -1); - producer.send(message); - producer.close(); - } - - @Test - public void testLegacyStoreConversion() throws Exception { - doTestScheduleRepeated(VERSION_LEGACY_JMS); - } - - public void doTestScheduleRepeated(File existingStore) throws Exception { - File testDir = new File("target/activemq-data/store/scheduler/versionDB"); - IOHelper.deleteFile(testDir); - IOHelper.copyFile(existingStore, testDir); - - final int NUMBER = 10; - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - - for (int i = 0; i < 3; ++i) { - JobSchedulerStoreImpl scheduler = new JobSchedulerStoreImpl(); - scheduler.setDirectory(testDir); - scheduler.setJournalMaxFileLength(1024 * 1024); - BrokerService broker = createBroker(scheduler); - broker.start(); - broker.waitUntilStarted(); - - final AtomicInteger count = new AtomicInteger(); - Connection connection = cf.createConnection(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createQueue("test.queue"); - - MessageConsumer consumer = session.createConsumer(queue); - - final CountDownLatch latch = new CountDownLatch(NUMBER); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - LOG.info("Received scheduled message: {}", message); - latch.countDown(); - count.incrementAndGet(); - } - }); - - connection.start(); - assertEquals(latch.getCount(), NUMBER); - latch.await(30, TimeUnit.SECONDS); - - connection.close(); - broker.stop(); - broker.waitUntilStopped(); - - assertEquals(0, latch.getCount()); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemeoryJmsSchedulerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemeoryJmsSchedulerTest.java deleted file mode 100644 index e67d799db1..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemeoryJmsSchedulerTest.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.activemq.broker.scheduler.memory; - -import org.apache.activemq.broker.scheduler.JmsSchedulerTest; - -/** - * Test for the In-Memory Scheduler variant. - */ -public class InMemeoryJmsSchedulerTest extends JmsSchedulerTest { - - @Override - protected boolean isPersistent() { - return false; - } - - @Override - public void testScheduleRestart() throws Exception { - // No persistence so scheduled jobs don't survive restart. - } - - @Override - public void testJobSchedulerStoreUsage() throws Exception { - // No store usage numbers for in-memory store. - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJmsCronSchedulerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJmsCronSchedulerTest.java deleted file mode 100644 index e3ec990a5f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJmsCronSchedulerTest.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.activemq.broker.scheduler.memory; - -import org.apache.activemq.broker.scheduler.JmsCronSchedulerTest; - -/** - * In memory version of the cron scheduler test. - */ -public class InMemoryJmsCronSchedulerTest extends JmsCronSchedulerTest { - - @Override - protected boolean isPersistent() { - return false; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerJmxManagementTests.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerJmxManagementTests.java deleted file mode 100644 index b2c2c367e3..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerJmxManagementTests.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.activemq.broker.scheduler.memory; - -import org.apache.activemq.broker.scheduler.JobSchedulerJmxManagementTests; - -/** - * Test for the In-Memory scheduler's JMX management features. - */ -public class InMemoryJobSchedulerJmxManagementTests extends JobSchedulerJmxManagementTests { - - @Override - protected boolean isPersistent() { - return false; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerManagementTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerManagementTest.java deleted file mode 100644 index bd7becd6b1..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerManagementTest.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.activemq.broker.scheduler.memory; - -import org.apache.activemq.broker.scheduler.JobSchedulerManagementTest; - -/** - * Tests management of in memory scheduler via JMS client. - */ -public class InMemoryJobSchedulerManagementTest extends JobSchedulerManagementTest { - - @Override - protected boolean isPersistent() { - return false; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerStoreTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerStoreTest.java deleted file mode 100644 index fbc11b162f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerStoreTest.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.activemq.broker.scheduler.memory; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import org.apache.activemq.broker.scheduler.Job; -import org.apache.activemq.broker.scheduler.JobScheduler; -import org.apache.activemq.util.ByteSequence; -import org.apache.activemq.util.IOHelper; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; - -/** - * - */ -public class InMemoryJobSchedulerStoreTest { - - private static final Logger LOG = LoggerFactory.getLogger(InMemoryJobSchedulerStoreTest.class); - - @Test(timeout = 120 * 1000) - public void testRestart() throws Exception { - InMemoryJobSchedulerStore store = new InMemoryJobSchedulerStore(); - File directory = new File("target/test/ScheduledDB"); - IOHelper.mkdirs(directory); - IOHelper.deleteChildren(directory); - store.setDirectory(directory); - final int NUMBER = 1000; - store.start(); - List list = new ArrayList<>(); - for (int i = 0; i < NUMBER; i++) { - ByteSequence buff = new ByteSequence(new String("testjob" + i).getBytes()); - list.add(buff); - } - - JobScheduler js = store.getJobScheduler("test"); - js.startDispatching(); - int count = 0; - long startTime = 10 * 60 * 1000; - long period = startTime; - for (ByteSequence job : list) { - js.schedule("id:" + (count++), job, "", startTime, period, -1); - } - - List test = js.getAllJobs(); - LOG.debug("Found {} jobs in the store before restart", test.size()); - assertEquals(list.size(), test.size()); - store.stop(); - store.start(); - js = store.getJobScheduler("test"); - test = js.getAllJobs(); - LOG.debug("Found {} jobs in the store after restart", test.size()); - assertEquals(0, test.size()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerTest.java deleted file mode 100644 index 3a9fe3effb..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerTest.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.activemq.broker.scheduler.memory; - -import org.apache.activemq.broker.scheduler.JobSchedulerStore; -import org.apache.activemq.broker.scheduler.JobSchedulerTest; - -/** - * In-Memory store based variation of the JobSchedulerTest - */ -public class InMemoryJobSchedulerTest extends JobSchedulerTest { - - @Override - public void testAddStopThenDeliver() throws Exception { - // In Memory store that's stopped doesn't retain the jobs. - } - - @Override - protected JobSchedulerStore createJobSchedulerStore() throws Exception { - return new InMemoryJobSchedulerStore(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerTxTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerTxTest.java deleted file mode 100644 index b1bb119da1..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/scheduler/memory/InMemoryJobSchedulerTxTest.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.activemq.broker.scheduler.memory; - -import org.apache.activemq.broker.scheduler.JobSchedulerTxTest; - -/** - * In memory version of the TX test case - */ -public class InMemoryJobSchedulerTxTest extends JobSchedulerTxTest { - - @Override - protected boolean isPersistent() { - return false; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/spring.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/spring.xml deleted file mode 100644 index 7d37217f47..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/spring.xml +++ /dev/null @@ -1,97 +0,0 @@ - - - - - - - - - - - - - - tcp://localhost:61616 - tcp://localhost:61636 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 10 - - - - - - - - - - - - - - - - - - org.apache.activemq.spring.Test.spring.topic - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/DefaultStoreBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/DefaultStoreBrokerTest.java deleted file mode 100644 index a3587ad0a0..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/DefaultStoreBrokerTest.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.activemq.broker.store; - -import java.net.URI; - -import junit.framework.Test; - -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.BrokerTest; - -/** - * Once the wire format is completed we can test against real persistence storage. - */ -public class DefaultStoreBrokerTest extends BrokerTest { - - @Override - protected BrokerService createBroker() throws Exception { - return BrokerFactory.createBroker(new URI("broker://()/localhost?deleteAllMessagesOnStartup=true")); - } - - protected BrokerService createRestartedBroker() throws Exception { - return BrokerFactory.createBroker(new URI("broker://()/localhost")); - } - - public static Test suite() { - return suite(DefaultStoreBrokerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/DefaultStoreRecoveryBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/DefaultStoreRecoveryBrokerTest.java deleted file mode 100644 index a7e0c323a2..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/DefaultStoreRecoveryBrokerTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.store; - -import java.net.URI; - -import junit.framework.Test; - -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.RecoveryBrokerTest; - -/** - * Used to verify that recovery works correctly against - */ -public class DefaultStoreRecoveryBrokerTest extends RecoveryBrokerTest { - - @Override - protected BrokerService createBroker() throws Exception { - return BrokerFactory.createBroker(new URI("broker://()/localhost?deleteAllMessagesOnStartup=true")); - } - - @Override - protected BrokerService createRestartedBroker() throws Exception { - return BrokerFactory.createBroker(new URI("broker://()/localhost")); - } - - public static Test suite() { - return suite(DefaultStoreRecoveryBrokerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/LoadTester.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/LoadTester.java deleted file mode 100644 index 56eac03745..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/LoadTester.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.activemq.broker.store; - -import javax.jms.BytesMessage; -import javax.jms.ConnectionFactory; -import javax.jms.DeliveryMode; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; - -import junit.framework.Test; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.JmsTestSupport; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.ProgressPrinter; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class LoadTester extends JmsTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(LoadTester.class); - - protected int messageSize = 1024 * 64; - protected int produceCount = 10000; - - @Override - protected BrokerService createBroker() throws Exception { - return BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/broker/store/loadtester.xml")); - } - - @Override - protected ConnectionFactory createConnectionFactory() throws URISyntaxException, IOException { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getServer().getConnectURI()); - factory.setUseAsyncSend(true); - return factory; - } - - public void testQueueSendThenAddConsumer() throws Exception { - ProgressPrinter printer = new ProgressPrinter(produceCount, 20); - - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - - connection.setUseCompression(false); - connection.getPrefetchPolicy().setAll(10); - connection.start(); - Session session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - - LOG.info("Sending " + produceCount + " messages that are " + (messageSize / 1024.0) + "k large, for a total of " + (produceCount * messageSize / (1024.0 * 1024.0)) + " megs of data."); - // Send a message to the broker. - long start = System.currentTimeMillis(); - for (int i = 0; i < produceCount; i++) { - printer.increment(); - BytesMessage msg = session.createBytesMessage(); - msg.writeBytes(new byte[messageSize]); - producer.send(msg); - } - long end1 = System.currentTimeMillis(); - - LOG.info("Produced messages/sec: " + (produceCount * 1000.0 / (end1 - start))); - - printer = new ProgressPrinter(produceCount, 10); - start = System.currentTimeMillis(); - MessageConsumer consumer = session.createConsumer(destination); - for (int i = 0; i < produceCount; i++) { - printer.increment(); - assertNotNull("Getting message: " + i, consumer.receive(20000)); - } - end1 = System.currentTimeMillis(); - LOG.info("Consumed messages/sec: " + (produceCount * 1000.0 / (end1 - start))); - - } - - public static Test suite() { - return suite(LoadTester.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/RecoverExpiredMessagesTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/RecoverExpiredMessagesTest.java deleted file mode 100644 index 91ca43075d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/RecoverExpiredMessagesTest.java +++ /dev/null @@ -1,144 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.store; - -import java.io.File; -import java.util.ArrayList; -import java.util.concurrent.TimeUnit; - -import junit.framework.Test; - -import org.apache.activemq.broker.BrokerRestartTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.StubConnection; -import org.apache.activemq.broker.region.policy.FilePendingQueueMessageStoragePolicy; -import org.apache.activemq.broker.region.policy.PendingQueueMessageStoragePolicy; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.VMPendingQueueMessageStoragePolicy; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ConnectionInfo; -import org.apache.activemq.command.ConsumerInfo; -import org.apache.activemq.command.Message; -import org.apache.activemq.command.MessageAck; -import org.apache.activemq.command.ProducerInfo; -import org.apache.activemq.command.SessionInfo; -import org.apache.activemq.openwire.OpenWireFormat; -import org.apache.activemq.store.PersistenceAdapter; -import org.apache.activemq.store.jdbc.DataSourceServiceSupport; -import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.util.IOHelper; - -public class RecoverExpiredMessagesTest extends BrokerRestartTestSupport { - - final ArrayList expected = new ArrayList<>(); - final ActiveMQDestination destination = new ActiveMQQueue("TEST"); - public PendingQueueMessageStoragePolicy queuePendingPolicy; - - @Override - protected void setUp() throws Exception { - setAutoFail(true); - super.setUp(); - } - - public void initCombosForTestRecovery() throws Exception { - addCombinationValues("queuePendingPolicy", new PendingQueueMessageStoragePolicy[]{new FilePendingQueueMessageStoragePolicy(), new VMPendingQueueMessageStoragePolicy()}); - PersistenceAdapter[] persistenceAdapters = new PersistenceAdapter[]{new KahaDBPersistenceAdapter(), new JDBCPersistenceAdapter(DataSourceServiceSupport.createDataSource(IOHelper.getDefaultDataDirectory()), new OpenWireFormat())}; - for (PersistenceAdapter adapter : persistenceAdapters) { - adapter.setDirectory(new File(IOHelper.getDefaultDataDirectory())); - } - addCombinationValues("persistenceAdapter", persistenceAdapters); - } - - public void testRecovery() throws Exception { - sendSomeMessagesThatWillExpireIn5AndThenOne(); - - broker.stop(); - broker.waitUntilStopped(); - TimeUnit.SECONDS.sleep(6); - broker = createRestartedBroker(); - broker.start(); - - consumeExpected(); - } - - private void consumeExpected() throws Exception { - // Setup the consumer and receive the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo, destination); - connection.send(consumerInfo); - - Message m = receiveMessage(connection); - assertNotNull("Should have received message " + expected.get(0) + " by now!", m); - assertEquals(expected.get(0), m.getMessageId().toString()); - MessageAck ack = createAck(consumerInfo, m, 1, MessageAck.STANDARD_ACK_TYPE); - connection.send(ack); - - assertNoMessagesLeft(connection); - connection.request(closeConnectionInfo(connectionInfo)); - } - - private void sendSomeMessagesThatWillExpireIn5AndThenOne() throws Exception { - - // Setup the producer and send the message. - StubConnection connection = createConnection(); - ConnectionInfo connectionInfo = createConnectionInfo(); - SessionInfo sessionInfo = createSessionInfo(connectionInfo); - ProducerInfo producerInfo = createProducerInfo(sessionInfo); - connection.send(connectionInfo); - connection.send(sessionInfo); - connection.send(producerInfo); - - int MESSAGE_COUNT = 10; - for (int i = 0; i < MESSAGE_COUNT; i++) { - Message message = createMessage(producerInfo, destination); - message.setExpiration(System.currentTimeMillis() + 5000); - message.setPersistent(true); - connection.send(message); - } - Message message = createMessage(producerInfo, destination); - message.setPersistent(true); - connection.send(message); - expected.add(message.getMessageId().toString()); - - connection.request(closeConnectionInfo(connectionInfo)); - } - - @Override - protected PolicyEntry getDefaultPolicy() { - PolicyEntry policy = super.getDefaultPolicy(); - policy.setPendingQueuePolicy(queuePendingPolicy); - policy.setExpireMessagesPeriod(0); - return policy; - } - - @Override - protected void configureBroker(BrokerService broker) throws Exception { - super.configureBroker(broker); - broker.setPersistenceAdapter(persistenceAdapter); - } - - public static Test suite() { - return suite(RecoverExpiredMessagesTest.class); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/kahabroker.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/kahabroker.xml deleted file mode 100644 index 4c8254b50d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/kahabroker.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/loadtester.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/loadtester.xml deleted file mode 100644 index 6383e84f1b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/store/loadtester.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/DestinationsPluginTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/DestinationsPluginTest.java deleted file mode 100644 index 79af861cec..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/DestinationsPluginTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.util; - -import org.apache.activemq.broker.BrokerPlugin; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.jmx.BrokerView; -import org.apache.activemq.command.ActiveMQDestination; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class DestinationsPluginTest { - - BrokerService broker; - - @Before - public void setUp() throws Exception { - broker = createBroker(); - broker.start(); - broker.waitUntilStarted(); - } - - @After - public void shutdown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } - - protected BrokerService createBroker() { - BrokerService broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(true); - broker.setPlugins(new BrokerPlugin[]{new DestinationsPlugin()}); - broker.setDataDirectory("target/test"); - return broker; - } - - @Test - public void testDestinationSave() throws Exception { - - BrokerView brokerView = broker.getAdminView(); - brokerView.addQueue("test-queue"); - - broker.stop(); - broker.waitUntilStopped(); - - broker = createBroker(); - broker.start(); - broker.waitUntilStarted(); - - ActiveMQDestination[] destinations = broker.getRegionBroker().getDestinations(); - for (ActiveMQDestination destination : destinations) { - if (destination.isQueue()) { - assertEquals("test-queue", destination.getPhysicalName()); - } - } - - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/PluginBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/PluginBrokerTest.java deleted file mode 100644 index 45abf362db..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/PluginBrokerTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.util; - -import javax.jms.JMSException; -import javax.jms.Message; -import java.net.URI; - -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQMessage; -import org.apache.activemq.test.JmsTopicSendReceiveTest; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * - */ -public class PluginBrokerTest extends JmsTopicSendReceiveTest { - - private static final Logger LOG = LoggerFactory.getLogger(PluginBrokerTest.class); - private BrokerService broker; - - @Override - protected void setUp() throws Exception { - broker = createBroker(); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - if (broker != null) { - broker.stop(); - } - } - - protected BrokerService createBroker() throws Exception { - return createBroker("org/apache/activemq/util/plugin-broker.xml"); - } - - protected BrokerService createBroker(String uri) throws Exception { - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } - - @Override - protected void assertMessageValid(int index, Message message) throws JMSException { - // check if broker path has been set - assertEquals("localhost", message.getStringProperty("BrokerPath")); - ActiveMQMessage amqMsg = (ActiveMQMessage) message; - if (index == 7) { - // check custom expiration - assertTrue("expiration is in range, depends on two distinct calls to System.currentTimeMillis", 1500 < amqMsg.getExpiration() - amqMsg.getTimestamp()); - } else if (index == 9) { - // check ceiling - assertTrue("expiration ceeling is in range, depends on two distinct calls to System.currentTimeMillis", 59500 < amqMsg.getExpiration() - amqMsg.getTimestamp()); - } else { - // check default expiration - assertEquals(1000, amqMsg.getExpiration() - amqMsg.getTimestamp()); - } - super.assertMessageValid(index, message); - } - - @Override - protected void sendMessage(int index, Message message) throws Exception { - if (index == 7) { - producer.send(producerDestination, message, Message.DEFAULT_DELIVERY_MODE, Message.DEFAULT_PRIORITY, 2000); - } else if (index == 9) { - producer.send(producerDestination, message, Message.DEFAULT_DELIVERY_MODE, Message.DEFAULT_PRIORITY, 200000); - } else { - super.sendMessage(index, message); - } - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/RedeliveryPluginTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/RedeliveryPluginTest.java deleted file mode 100644 index 62832d8c56..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/RedeliveryPluginTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.util; - -import junit.framework.TestCase; - -import org.apache.activemq.RedeliveryPolicy; -import org.apache.activemq.broker.Broker; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.ErrorBroker; -import org.apache.activemq.broker.region.policy.RedeliveryPolicyMap; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class RedeliveryPluginTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(RedeliveryPluginTest.class); - RedeliveryPlugin underTest = new RedeliveryPlugin(); - - public void testInstallPluginValidation() throws Exception { - RedeliveryPolicyMap redeliveryPolicyMap = new RedeliveryPolicyMap(); - RedeliveryPolicy defaultEntry = new RedeliveryPolicy(); - defaultEntry.setInitialRedeliveryDelay(500); - redeliveryPolicyMap.setDefaultEntry(defaultEntry); - underTest.setRedeliveryPolicyMap(redeliveryPolicyMap); - - final BrokerService brokerService = new BrokerService(); - brokerService.setSchedulerSupport(false); - Broker broker = new ErrorBroker("hi") { - @Override - public BrokerService getBrokerService() { - return brokerService; - } - }; - - try { - underTest.installPlugin(broker); - fail("expect exception on no scheduler support"); - } catch (Exception expected) { - LOG.info("expected: " + expected); - } - - brokerService.setSchedulerSupport(true); - try { - underTest.installPlugin(broker); - fail("expect exception on small initial delay"); - } catch (Exception expected) { - LOG.info("expected: " + expected); - } - - defaultEntry.setInitialRedeliveryDelay(5000); - defaultEntry.setRedeliveryDelay(500); - brokerService.setSchedulerSupport(true); - try { - underTest.installPlugin(broker); - fail("expect exception on small redelivery delay"); - } catch (Exception expected) { - LOG.info("expected: " + expected); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/TimeStampingBrokerPluginTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/TimeStampingBrokerPluginTest.java deleted file mode 100644 index 81abfb30fe..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/TimeStampingBrokerPluginTest.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.activemq.broker.util; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerPlugin; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.broker.region.policy.DeadLetterStrategy; -import org.apache.activemq.broker.region.policy.IndividualDeadLetterStrategy; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class TimeStampingBrokerPluginTest extends TestCase { - - BrokerService broker; - TransportConnector tcpConnector; - MessageProducer producer; - MessageConsumer consumer; - Connection connection; - Session session; - Destination destination; - String queue = "TEST.FOO"; - long expiry = 500; - - @Override - @Before - public void setUp() throws Exception { - TimeStampingBrokerPlugin tsbp = new TimeStampingBrokerPlugin(); - tsbp.setZeroExpirationOverride(expiry); - tsbp.setTtlCeiling(expiry); - - broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(true); - broker.setPlugins(new BrokerPlugin[]{tsbp}); - tcpConnector = broker.addConnector("tcp://localhost:0"); - - // Add policy and individual DLQ strategy - PolicyEntry policy = new PolicyEntry(); - DeadLetterStrategy strategy = new IndividualDeadLetterStrategy(); - strategy.setProcessExpired(true); - ((IndividualDeadLetterStrategy) strategy).setUseQueueForQueueMessages(true); - ((IndividualDeadLetterStrategy) strategy).setQueuePrefix("DLQ."); - strategy.setProcessNonPersistent(true); - policy.setDeadLetterStrategy(strategy); - - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - - broker.setDestinationPolicy(pMap); - - broker.start(); - // Create a ConnectionFactory - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(tcpConnector.getConnectUri()); - - // Create a Connection - connection = connectionFactory.createConnection(); - connection.start(); - - // Create a Session - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // Create the destination Queue - destination = session.createQueue(queue); - - // Create a MessageProducer from the Session to the Topic or Queue - producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - } - - @Override - @After - public void tearDown() throws Exception { - // Clean up - producer.close(); - consumer.close(); - session.close(); - connection.close(); - broker.stop(); - } - - @Test - public void testExpirationSet() throws Exception { - - // Create a messages - Message sentMessage = session.createMessage(); - - // Tell the producer to send the message - long beforeSend = System.currentTimeMillis(); - producer.send(sentMessage); - - // Create a MessageConsumer from the Session to the Topic or Queue - consumer = session.createConsumer(destination); - - // Wait for a message - Message receivedMessage = consumer.receive(1000); - - // assert we got the same message ID we sent - assertEquals(sentMessage.getJMSMessageID(), receivedMessage.getJMSMessageID()); - - // assert message timestamp is in window - assertTrue("Expiration should be not null" + receivedMessage.getJMSExpiration() + "\n", Long.valueOf(receivedMessage.getJMSExpiration()) != null); - - // assert message expiration is in window - assertTrue("Before send: " + beforeSend + " Msg ts: " + receivedMessage.getJMSTimestamp() + " Msg Expiry: " + receivedMessage.getJMSExpiration(), beforeSend <= receivedMessage.getJMSExpiration() && receivedMessage.getJMSExpiration() <= (receivedMessage.getJMSTimestamp() + expiry)); - } - - @Test - public void testExpirationCelingSet() throws Exception { - - // Create a messages - Message sentMessage = session.createMessage(); - // Tell the producer to send the message - long beforeSend = System.currentTimeMillis(); - long sendExpiry = beforeSend + (expiry * 22); - sentMessage.setJMSExpiration(sendExpiry); - - producer.send(sentMessage); - - // Create a MessageConsumer from the Session to the Topic or Queue - consumer = session.createConsumer(destination); - - // Wait for a message - Message receivedMessage = consumer.receive(1000); - - // assert we got the same message ID we sent - assertEquals(sentMessage.getJMSMessageID(), receivedMessage.getJMSMessageID()); - - // assert message timestamp is in window - assertTrue("Expiration should be not null" + receivedMessage.getJMSExpiration() + "\n", Long.valueOf(receivedMessage.getJMSExpiration()) != null); - - // assert message expiration is in window - assertTrue("Sent expiry: " + sendExpiry + " Recv ts: " + receivedMessage.getJMSTimestamp() + " Recv expiry: " + receivedMessage.getJMSExpiration(), beforeSend <= receivedMessage.getJMSExpiration() && receivedMessage.getJMSExpiration() <= (receivedMessage.getJMSTimestamp() + expiry)); - } - - @Test - public void testExpirationDLQ() throws Exception { - - // Create a messages - Message sentMessage = session.createMessage(); - // Tell the producer to send the message - long beforeSend = System.currentTimeMillis(); - long sendExpiry = beforeSend + expiry; - sentMessage.setJMSExpiration(sendExpiry); - - producer.send(sentMessage); - - // Create a MessageConsumer from the Session to the Topic or Queue - consumer = session.createConsumer(destination); - - Thread.sleep(expiry + 250); - - // Wait for a message - Message receivedMessage = consumer.receive(1000); - - // Message should roll to DLQ - assertNull(receivedMessage); - - // Close old consumer, setup DLQ listener - consumer.close(); - consumer = session.createConsumer(session.createQueue("DLQ." + queue)); - - // Get message from DLQ - receivedMessage = consumer.receive(1000); - - // assert we got the same message ID we sent - assertEquals(sentMessage.getJMSMessageID(), receivedMessage.getJMSMessageID()); - - // assert message timestamp is in window - //System.out.println("Recv: " + receivedMessage.getJMSExpiration()); - assertEquals("Expiration should be zero" + receivedMessage.getJMSExpiration() + "\n", receivedMessage.getJMSExpiration(), 0); - - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/TraceBrokerPathPluginTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/TraceBrokerPathPluginTest.java deleted file mode 100644 index 7171ddd57b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/util/TraceBrokerPathPluginTest.java +++ /dev/null @@ -1,130 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.broker.util; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerPlugin; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -/** - * Tests TraceBrokerPathPlugin by creating two brokers linked by a network connector, and checking to see if the consuming end receives the expected value in the trace property - * - * @author Raul Kripalani - */ -public class TraceBrokerPathPluginTest extends TestCase { - - BrokerService brokerA; - BrokerService brokerB; - TransportConnector tcpConnectorA; - TransportConnector tcpConnectorB; - MessageProducer producer; - MessageConsumer consumer; - Connection connectionA; - Connection connectionB; - Session sessionA; - Session sessionB; - String queue = "TEST.FOO"; - String traceProperty = "BROKER_PATH"; - - @Override - @Before - public void setUp() throws Exception { - TraceBrokerPathPlugin tbppA = new TraceBrokerPathPlugin(); - tbppA.setStampProperty(traceProperty); - - TraceBrokerPathPlugin tbppB = new TraceBrokerPathPlugin(); - tbppB.setStampProperty(traceProperty); - - brokerA = new BrokerService(); - brokerA.setBrokerName("brokerA"); - brokerA.setPersistent(false); - brokerA.setUseJmx(true); - brokerA.setPlugins(new BrokerPlugin[]{tbppA}); - tcpConnectorA = brokerA.addConnector("tcp://localhost:0"); - - brokerB = new BrokerService(); - brokerB.setBrokerName("brokerB"); - brokerB.setPersistent(false); - brokerB.setUseJmx(true); - brokerB.setPlugins(new BrokerPlugin[]{tbppB}); - tcpConnectorB = brokerB.addConnector("tcp://localhost:0"); - - brokerA.addNetworkConnector("static:(" + tcpConnectorB.getConnectUri().toString() + ")"); - - brokerB.start(); - brokerB.waitUntilStarted(); - brokerA.start(); - brokerA.waitUntilStarted(); - - // Initialise connection to A and MessageProducer - connectionA = new ActiveMQConnectionFactory(tcpConnectorA.getConnectUri()).createConnection(); - connectionA.start(); - sessionA = connectionA.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = sessionA.createProducer(sessionA.createQueue(queue)); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - - // Initialise connection to B and MessageConsumer - connectionB = new ActiveMQConnectionFactory(tcpConnectorB.getConnectUri()).createConnection(); - connectionB.start(); - sessionB = connectionB.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = sessionB.createConsumer(sessionB.createQueue(queue)); - - } - - @Override - @After - public void tearDown() throws Exception { - // Clean up - producer.close(); - consumer.close(); - sessionA.close(); - sessionB.close(); - connectionA.close(); - connectionB.close(); - brokerA.stop(); - brokerB.stop(); - } - - @Test - public void testTraceBrokerPathPlugin() throws Exception { - Message sentMessage = sessionA.createMessage(); - producer.send(sentMessage); - Message receivedMessage = consumer.receive(1000); - - // assert we got the message - assertNotNull(receivedMessage); - - // assert we got the same message ID we sent - assertEquals(sentMessage.getJMSMessageID(), receivedMessage.getJMSMessageID()); - - assertEquals("brokerA,brokerB", receivedMessage.getStringProperty(traceProperty)); - - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerPropertiesTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerPropertiesTest.java deleted file mode 100644 index c1e674e80a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerPropertiesTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.config; - -import javax.jms.Connection; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerRegistry; -import org.apache.activemq.broker.BrokerService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class BrokerPropertiesTest extends TestCase { - - private static final transient Logger LOG = LoggerFactory.getLogger(BrokerPropertiesTest.class); - - public void testPropertiesFile() throws Exception { - BrokerService broker = BrokerFactory.createBroker("properties:org/apache/activemq/config/broker.properties"); - - LOG.info("Created broker: " + broker); - assertNotNull(broker); - - assertEquals("isUseJmx()", false, broker.isUseJmx()); - assertEquals("isPersistent()", false, broker.isPersistent()); - assertEquals("getBrokerName()", "Cheese", broker.getBrokerName()); - broker.stop(); - } - - public void testVmBrokerPropertiesFile() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?brokerConfig=properties:org/apache/activemq/config/broker.properties"); - Connection connection = factory.createConnection(); - BrokerService broker = BrokerRegistry.getInstance().lookup("Cheese"); - LOG.info("Found broker : " + broker); - assertNotNull(broker); - - assertEquals("isUseJmx()", false, broker.isUseJmx()); - assertEquals("isPersistent()", false, broker.isPersistent()); - assertEquals("getBrokerName()", "Cheese", broker.getBrokerName()); - connection.close(); - broker.stop(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerXmlConfigFromJNDITest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerXmlConfigFromJNDITest.java deleted file mode 100644 index 883b1a9e02..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerXmlConfigFromJNDITest.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.activemq.config; - -import javax.naming.Context; -import javax.naming.InitialContext; -import java.io.File; -import java.util.Hashtable; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.test.JmsTopicSendReceiveWithTwoConnectionsTest; - -/** - * - */ -public class BrokerXmlConfigFromJNDITest extends JmsTopicSendReceiveWithTwoConnectionsTest { - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - assertBaseDirectoryContainsSpaces(); - - // we could put these properties into a jndi.properties - // on the classpath instead - Hashtable properties = new Hashtable<>(); - properties.put("java.naming.factory.initial", "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); - - // configure the embedded broker using an XML config file - // which is either a URL or a resource on the classpath - File f = new File(System.getProperty("basedir", "."), "/src/test/resources/activemq.xml"); - properties.put(Context.PROVIDER_URL, "vm://localhost?brokerConfig=xbean:" + f.toURI()); - - InitialContext context = new InitialContext(properties); - ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory) context.lookup("ConnectionFactory"); - - // END SNIPPET: example - return connectionFactory; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerXmlConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerXmlConfigTest.java deleted file mode 100644 index 1509e04d02..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/BrokerXmlConfigTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.config; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.test.JmsTopicSendReceiveWithTwoConnectionsTest; - -/** - * - */ -public class BrokerXmlConfigTest extends JmsTopicSendReceiveWithTwoConnectionsTest { - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - // START SNIPPET: bean - - // configure the connection factory using - // normal Java Bean property methods - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); - - // configure the embedded broker using an XML config file - // which is either a URL or a resource on the classpath - - // TODO ... - - //connectionFactory.setBrokerXmlConfig("file:src/sample-conf/default.xml"); - - // you only need to configure the broker URL if you wish to change the - // default connection mechanism, which in this test case we do - connectionFactory.setBrokerURL("vm://localhost"); - - // END SNIPPET: bean - return connectionFactory; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/ConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/ConfigTest.java deleted file mode 100644 index 1309f4c41d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/ConfigTest.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.activemq.config; - -import javax.jms.JMSException; -import javax.jms.MessageConsumer; -import javax.jms.Session; -import javax.jms.Topic; -import javax.sql.DataSource; -import java.io.File; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.ResultSet; -import java.util.List; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.broker.region.policy.FixedSizedSubscriptionRecoveryPolicy; -import org.apache.activemq.broker.region.policy.LastImageSubscriptionRecoveryPolicy; -import org.apache.activemq.broker.region.policy.NoSubscriptionRecoveryPolicy; -import org.apache.activemq.broker.region.policy.RoundRobinDispatchPolicy; -import org.apache.activemq.broker.region.policy.SimpleDispatchPolicy; -import org.apache.activemq.broker.region.policy.StrictOrderDispatchPolicy; -import org.apache.activemq.broker.region.policy.SubscriptionRecoveryPolicy; -import org.apache.activemq.broker.region.policy.TimedSubscriptionRecoveryPolicy; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.store.PersistenceAdapter; -import org.apache.activemq.store.jdbc.DefaultDatabaseLocker; -import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; -import org.apache.activemq.store.jdbc.adapter.TransactDatabaseLocker; -import org.apache.activemq.store.journal.JournalPersistenceAdapter; -import org.apache.activemq.store.memory.MemoryPersistenceAdapter; -import org.apache.activemq.transport.tcp.TcpTransportServer; -import org.apache.activemq.usage.SystemUsage; -import org.apache.activemq.xbean.BrokerFactoryBean; -import org.jmock.Expectations; -import org.jmock.Mockery; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.FileSystemResource; -import org.springframework.core.io.Resource; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -public class ConfigTest { - - protected static final String JOURNAL_ROOT = "target/test-data/"; - protected static final String DERBY_ROOT = "target/test-data/"; - protected static final String CONF_ROOT = "src/test/resources/org/apache/activemq/config/sample-conf/"; - private static final Logger LOG = LoggerFactory.getLogger(ConfigTest.class); - - static { - System.setProperty("javax.net.ssl.trustStore", "src/test/resources/client.keystore"); - System.setProperty("javax.net.ssl.trustStorePassword", "password"); - System.setProperty("javax.net.ssl.trustStoreType", "jks"); - System.setProperty("javax.net.ssl.keyStore", "src/test/resources/server.keystore"); - System.setProperty("javax.net.ssl.keyStorePassword", "password"); - System.setProperty("javax.net.ssl.keyStoreType", "jks"); - } - - /* - * IMPORTANT NOTE: Assertions checking for the existence of the derby - * directory will fail if the first derby directory is not created under - * target/test-data/. The test in unable to change the derby root directory - * for succeeding creation. It uses the first created directory as the root. - */ - - /* - * This tests creating a journal persistence adapter using the persistence - * adapter factory bean - */ - @Test - public void testJournaledJDBCConfig() throws Exception { - - File journalFile = new File(JOURNAL_ROOT + "testJournaledJDBCConfig/journal"); - recursiveDelete(journalFile); - - File derbyFile = new File(DERBY_ROOT + "testJournaledJDBCConfig/derbydb"); // Default - recursiveDelete(derbyFile); - - BrokerService broker; - broker = createBroker(new FileSystemResource(CONF_ROOT + "journaledjdbc-example.xml")); - try { - assertEquals("Broker Config Error (brokerName)", "brokerJournaledJDBCConfigTest", broker.getBrokerName()); - - PersistenceAdapter adapter = broker.getPersistenceAdapter(); - - assertTrue("Should have created a journal persistence adapter", adapter instanceof JournalPersistenceAdapter); - assertTrue("Should have created a derby directory at " + derbyFile.getAbsolutePath(), derbyFile.exists()); - assertTrue("Should have created a journal directory at " + journalFile.getAbsolutePath(), journalFile.exists()); - - // Check persistence factory configurations - broker.getPersistenceAdapter(); - - assertTrue(broker.getSystemUsage().getStoreUsage().getStore() instanceof JournalPersistenceAdapter); - - LOG.info("Success"); - } finally { - if (broker != null) { - broker.stop(); - } - } - } - - @Test - public void testJdbcLockConfigOverride() throws Exception { - - JDBCPersistenceAdapter adapter = new JDBCPersistenceAdapter(); - Mockery context = new Mockery(); - final DataSource dataSource = context.mock(DataSource.class); - final Connection connection = context.mock(Connection.class); - final DatabaseMetaData metadata = context.mock(DatabaseMetaData.class); - final ResultSet result = context.mock(ResultSet.class); - adapter.setDataSource(dataSource); - adapter.setCreateTablesOnStartup(false); - - context.checking(new Expectations() {{ - allowing(dataSource).getConnection(); - will(returnValue(connection)); - allowing(connection).getMetaData(); - will(returnValue(metadata)); - allowing(connection); - allowing(metadata).getDriverName(); - will(returnValue("Microsoft_SQL_Server_2005_jdbc_driver")); - allowing(result).next(); - will(returnValue(true)); - }}); - - adapter.start(); - assertTrue("has the locker override", adapter.getLocker() instanceof TransactDatabaseLocker); - adapter.stop(); - } - - /* - * This tests configuring the different broker properties using - * xbeans-spring - */ - @Test - public void testBrokerConfig() throws Exception { - ActiveMQTopic dest; - BrokerService broker; - - File journalFile = new File(JOURNAL_ROOT); - recursiveDelete(journalFile); - - // Create broker from resource - // System.out.print("Creating broker... "); - broker = createBroker("org/apache/activemq/config/example.xml"); - LOG.info("Success"); - - try { - // Check broker configuration - // System.out.print("Checking broker configurations... "); - assertEquals("Broker Config Error (brokerName)", "brokerConfigTest", broker.getBrokerName()); - assertEquals("Broker Config Error (populateJMSXUserID)", false, broker.isPopulateJMSXUserID()); - assertEquals("Broker Config Error (useLoggingForShutdownErrors)", true, broker.isUseLoggingForShutdownErrors()); - assertEquals("Broker Config Error (useJmx)", true, broker.isUseJmx()); - assertEquals("Broker Config Error (persistent)", false, broker.isPersistent()); - assertEquals("Broker Config Error (useShutdownHook)", false, broker.isUseShutdownHook()); - assertEquals("Broker Config Error (deleteAllMessagesOnStartup)", true, broker.isDeleteAllMessagesOnStartup()); - LOG.info("Success"); - - // Check specific vm transport - // System.out.print("Checking vm connector... "); - assertEquals("Should have a specific VM Connector", "vm://javacoola", broker.getVmConnectorURI().toString()); - LOG.info("Success"); - - // Check transport connectors list - // System.out.print("Checking transport connectors... "); - List connectors = broker.getTransportConnectors(); - assertTrue("Should have created at least 3 connectors", connectors.size() >= 3); - assertTrue("1st connector should be TcpTransportServer", connectors.get(0).getServer() instanceof TcpTransportServer); - assertTrue("2nd connector should be TcpTransportServer", connectors.get(1).getServer() instanceof TcpTransportServer); - assertTrue("3rd connector should be TcpTransportServer", connectors.get(2).getServer() instanceof TcpTransportServer); - - // Check network connectors - // System.out.print("Checking network connectors... "); - List networkConnectors = broker.getNetworkConnectors(); - assertEquals("Should have a single network connector", 1, networkConnectors.size()); - LOG.info("Success"); - - // Check dispatch policy configuration - // System.out.print("Checking dispatch policies... "); - - dest = new ActiveMQTopic("Topic.SimpleDispatch"); - assertTrue("Should have a simple dispatch policy for " + dest.getTopicName(), broker.getDestinationPolicy().getEntryFor(dest).getDispatchPolicy() instanceof SimpleDispatchPolicy); - - dest = new ActiveMQTopic("Topic.RoundRobinDispatch"); - assertTrue("Should have a round robin dispatch policy for " + dest.getTopicName(), broker.getDestinationPolicy().getEntryFor(dest).getDispatchPolicy() instanceof RoundRobinDispatchPolicy); - - dest = new ActiveMQTopic("Topic.StrictOrderDispatch"); - assertTrue("Should have a strict order dispatch policy for " + dest.getTopicName(), broker.getDestinationPolicy().getEntryFor(dest).getDispatchPolicy() instanceof StrictOrderDispatchPolicy); - LOG.info("Success"); - - // Check subscription policy configuration - // System.out.print("Checking subscription recovery policies... "); - SubscriptionRecoveryPolicy subsPolicy; - - dest = new ActiveMQTopic("Topic.FixedSizedSubs"); - subsPolicy = broker.getDestinationPolicy().getEntryFor(dest).getSubscriptionRecoveryPolicy(); - assertTrue("Should have a fixed sized subscription recovery policy for " + dest.getTopicName(), subsPolicy instanceof FixedSizedSubscriptionRecoveryPolicy); - assertEquals("FixedSizedSubsPolicy Config Error (maximumSize)", 2000000, ((FixedSizedSubscriptionRecoveryPolicy) subsPolicy).getMaximumSize()); - assertEquals("FixedSizedSubsPolicy Config Error (useSharedBuffer)", false, ((FixedSizedSubscriptionRecoveryPolicy) subsPolicy).isUseSharedBuffer()); - - dest = new ActiveMQTopic("Topic.LastImageSubs"); - subsPolicy = broker.getDestinationPolicy().getEntryFor(dest).getSubscriptionRecoveryPolicy(); - assertTrue("Should have a last image subscription recovery policy for " + dest.getTopicName(), subsPolicy instanceof LastImageSubscriptionRecoveryPolicy); - - dest = new ActiveMQTopic("Topic.NoSubs"); - subsPolicy = broker.getDestinationPolicy().getEntryFor(dest).getSubscriptionRecoveryPolicy(); - assertTrue("Should have no subscription recovery policy for " + dest.getTopicName(), subsPolicy instanceof NoSubscriptionRecoveryPolicy); - - dest = new ActiveMQTopic("Topic.TimedSubs"); - subsPolicy = broker.getDestinationPolicy().getEntryFor(dest).getSubscriptionRecoveryPolicy(); - assertTrue("Should have a timed subscription recovery policy for " + dest.getTopicName(), subsPolicy instanceof TimedSubscriptionRecoveryPolicy); - assertEquals("TimedSubsPolicy Config Error (recoverDuration)", 25000, ((TimedSubscriptionRecoveryPolicy) subsPolicy).getRecoverDuration()); - LOG.info("Success"); - - // Check usage manager - // System.out.print("Checking memory manager configurations... "); - SystemUsage systemUsage = broker.getSystemUsage(); - assertTrue("Should have a SystemUsage", systemUsage != null); - assertEquals("SystemUsage Config Error (MemoryUsage.limit)", 1024 * 1024 * 10, systemUsage.getMemoryUsage().getLimit()); - assertEquals("SystemUsage Config Error (MemoryUsage.percentUsageMinDelta)", 20, systemUsage.getMemoryUsage().getPercentUsageMinDelta()); - assertEquals("SystemUsage Config Error (TempUsage.limit)", 1024 * 1024 * 100, systemUsage.getTempUsage().getLimit()); - assertEquals("SystemUsage Config Error (StoreUsage.limit)", 1024 * 1024 * 1024, systemUsage.getStoreUsage().getLimit()); - assertEquals("SystemUsage Config Error (StoreUsage.name)", "foo", systemUsage.getStoreUsage().getName()); - - assertNotNull(systemUsage.getStoreUsage().getStore()); - assertTrue(systemUsage.getStoreUsage().getStore() instanceof MemoryPersistenceAdapter); - - LOG.info("Success"); - - } finally { - if (broker != null) { - broker.stop(); - } - } - } - - /* - * This tests creating a journal persistence adapter using xbeans-spring - */ - @Test - public void testJournalConfig() throws Exception { - File journalFile = new File(JOURNAL_ROOT + "testJournalConfig/journal"); - recursiveDelete(journalFile); - - BrokerService broker; - broker = createBroker(new FileSystemResource(CONF_ROOT + "journal-example.xml")); - try { - assertEquals("Broker Config Error (brokerName)", "brokerJournalConfigTest", broker.getBrokerName()); - - PersistenceAdapter adapter = broker.getPersistenceAdapter(); - - assertTrue("Should have created a journal persistence adapter", adapter instanceof JournalPersistenceAdapter); - assertTrue("Should have created a journal directory at " + journalFile.getAbsolutePath(), journalFile.exists()); - - LOG.info("Success"); - } finally { - if (broker != null) { - broker.stop(); - } - } - } - - /* - * This tests creating a memory persistence adapter using xbeans-spring - */ - @Test - public void testMemoryConfig() throws Exception { - File journalFile = new File(JOURNAL_ROOT + "testMemoryConfig"); - recursiveDelete(journalFile); - - File derbyFile = new File(DERBY_ROOT + "testMemoryConfig"); - recursiveDelete(derbyFile); - - BrokerService broker; - broker = createBroker(new FileSystemResource(CONF_ROOT + "memory-example.xml")); - - try { - assertEquals("Broker Config Error (brokerName)", "brokerMemoryConfigTest", broker.getBrokerName()); - - PersistenceAdapter adapter = broker.getPersistenceAdapter(); - - assertTrue("Should have created a memory persistence adapter", adapter instanceof MemoryPersistenceAdapter); - assertTrue("Should have not created a derby directory at " + derbyFile.getAbsolutePath(), !derbyFile.exists()); - assertTrue("Should have not created a journal directory at " + journalFile.getAbsolutePath(), !journalFile.exists()); - - LOG.info("Success"); - } finally { - if (broker != null) { - broker.stop(); - } - } - } - - @Test - public void testConnectorConfig() throws Exception { - - File journalFile = new File(JOURNAL_ROOT + "testMemoryConfig"); - recursiveDelete(journalFile); - - File derbyFile = new File(DERBY_ROOT + "testMemoryConfig"); - recursiveDelete(derbyFile); - - final int MAX_PRODUCERS = 5; - final int MAX_CONSUMERS = 10; - - BrokerService broker = createBroker(new FileSystemResource(CONF_ROOT + "connector-properties.xml")); - broker.start(); - try { - - assertEquals(broker.getTransportConnectorByScheme("tcp").getMaximumProducersAllowedPerConnection(), MAX_PRODUCERS); - assertEquals(broker.getTransportConnectorByScheme("tcp").getMaximumConsumersAllowedPerConnection(), MAX_CONSUMERS); - - ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61631"); - javax.jms.Connection connection = activeMQConnectionFactory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic("test.foo"); - - for (int i = 0; i < MAX_PRODUCERS; i++) { - session.createProducer(topic); - } - - try { - session.createProducer(topic); - fail("Should have got an exception on exceeding MAX_PRODUCERS"); - } catch (JMSException expected) { - } - - try { - for (int i = 0; i < (MAX_CONSUMERS + 1); i++) { - MessageConsumer consumer = session.createConsumer(topic); - assertNotNull(consumer); - } - fail("Should have caught an exception"); - } catch (JMSException e) { - } - - LOG.info("Success"); - } finally { - broker.stop(); - } - } - - @Test - public void testXmlConfigHelper() throws Exception { - BrokerService broker; - - broker = createBroker(new FileSystemResource(CONF_ROOT + "memory-example.xml")); - try { - assertEquals("Broker Config Error (brokerName)", "brokerMemoryConfigTest", broker.getBrokerName()); - } finally { - if (broker != null) { - broker.stop(); - } - } - - broker = createBroker("org/apache/activemq/config/config.xml"); - try { - assertEquals("Broker Config Error (brokerName)", "brokerXmlConfigHelper", broker.getBrokerName()); - } finally { - if (broker != null) { - broker.stop(); - } - } - } - - /* - * TODO: Create additional tests for forwarding bridges - */ - - protected static void recursiveDelete(File file) { - if (file.isDirectory()) { - File[] files = file.listFiles(); - for (int i = 0; i < files.length; i++) { - recursiveDelete(files[i]); - } - } - file.delete(); - } - - protected BrokerService createBroker(String resource) throws Exception { - return createBroker(new ClassPathResource(resource)); - } - - protected BrokerService createBroker(Resource resource) throws Exception { - BrokerFactoryBean factory = new BrokerFactoryBean(resource); - factory.afterPropertiesSet(); - - BrokerService broker = factory.getBroker(); - - assertTrue("Should have a broker!", broker != null); - - // Broker is already started by default when using the XML file - // broker.start(); - - return broker; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/ConfigUsingDestinationOptionsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/ConfigUsingDestinationOptionsTest.java deleted file mode 100644 index c92685a7c0..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/ConfigUsingDestinationOptionsTest.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.activemq.config; - -import javax.jms.Connection; -import javax.jms.InvalidSelectorException; -import javax.jms.JMSException; -import javax.jms.Session; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ActiveMQMessageConsumer; -import org.apache.activemq.command.ActiveMQQueue; -import org.junit.Test; - -public class ConfigUsingDestinationOptionsTest extends TestCase { - - @Test(timeout = 60000) - public void testValidSelectorConfig() throws JMSException { - ActiveMQQueue queue = new ActiveMQQueue("TEST.FOO?consumer.selector=test=1"); - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection conn = factory.createConnection(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - - ActiveMQMessageConsumer cons; - // JMS selector should be priority - cons = (ActiveMQMessageConsumer) sess.createConsumer(queue, "test=2"); - assertEquals("test=2", cons.getMessageSelector()); - - // Test setting using JMS destinations - cons = (ActiveMQMessageConsumer) sess.createConsumer(queue); - assertEquals("test=1", cons.getMessageSelector()); - } - - @Test(timeout = 60000) - public void testInvalidSelectorConfig() throws JMSException { - ActiveMQQueue queue = new ActiveMQQueue("TEST.FOO?consumer.selector=test||1"); - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection conn = factory.createConnection(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - - ActiveMQMessageConsumer cons; - // JMS selector should be priority - try { - cons = (ActiveMQMessageConsumer) sess.createConsumer(queue, "test||1"); - fail("Selector should be invalid" + cons); - } catch (InvalidSelectorException e) { - - } - - // Test setting using JMS destinations - try { - cons = (ActiveMQMessageConsumer) sess.createConsumer(queue); - fail("Selector should be invalid" + cons); - } catch (InvalidSelectorException e) { - - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/JDBCConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/JDBCConfigTest.java deleted file mode 100644 index 507869779e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/JDBCConfigTest.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.activemq.config; - -import java.io.File; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.store.PersistenceAdapter; -import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; -import org.apache.activemq.wireformat.ObjectStreamWireFormat; -import org.apache.activemq.xbean.BrokerFactoryBean; -import org.apache.derby.jdbc.EmbeddedDataSource; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.FileSystemResource; -import org.springframework.core.io.Resource; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class JDBCConfigTest { - - protected static final String JOURNAL_ROOT = "target/test-data/"; - protected static final String DERBY_ROOT = "target/test-data/"; - protected static final String CONF_ROOT = "src/test/resources/org/apache/activemq/config/sample-conf/"; - private static final Logger LOG = LoggerFactory.getLogger(JDBCConfigTest.class); - - /* - * This tests creating a jdbc persistence adapter using xbeans-spring - */ - @Test - public void testJdbcConfig() throws Exception { - File journalFile = new File(JOURNAL_ROOT + "testJDBCConfig/journal"); - recursiveDelete(journalFile); - - File derbyFile = new File(DERBY_ROOT + "testJDBCConfig/derbydb"); // Default - recursiveDelete(derbyFile); - - BrokerService broker; - broker = createBroker(new FileSystemResource(CONF_ROOT + "jdbc-example.xml")); - try { - assertEquals("Broker Config Error (brokerName)", "brokerJdbcConfigTest", broker.getBrokerName()); - - PersistenceAdapter adapter = broker.getPersistenceAdapter(); - - assertTrue("Should have created a jdbc persistence adapter", adapter instanceof JDBCPersistenceAdapter); - assertEquals("JDBC Adapter Config Error (cleanupPeriod)", 60000, ((JDBCPersistenceAdapter) adapter).getCleanupPeriod()); - assertTrue("Should have created an EmbeddedDataSource", ((JDBCPersistenceAdapter) adapter).getDataSource() instanceof EmbeddedDataSource); - assertTrue("Should have created a DefaultWireFormat", ((JDBCPersistenceAdapter) adapter).getWireFormat() instanceof ObjectStreamWireFormat); - - LOG.info("Success"); - } finally { - if (broker != null) { - broker.stop(); - } - } - } - - protected static void recursiveDelete(File file) { - if (file.isDirectory()) { - File[] files = file.listFiles(); - for (int i = 0; i < files.length; i++) { - recursiveDelete(files[i]); - } - } - file.delete(); - } - - protected BrokerService createBroker(String resource) throws Exception { - return createBroker(new ClassPathResource(resource)); - } - - protected BrokerService createBroker(Resource resource) throws Exception { - BrokerFactoryBean factory = new BrokerFactoryBean(resource); - factory.afterPropertiesSet(); - - BrokerService broker = factory.getBroker(); - - assertTrue("Should have a broker!", broker != null); - - // Broker is already started by default when using the XML file - // broker.start(); - - return broker; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/broker.properties b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/broker.properties deleted file mode 100644 index 921671f2a9..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/broker.properties +++ /dev/null @@ -1,21 +0,0 @@ -## --------------------------------------------------------------------------- -## Licensed to the Apache Software Foundation (ASF) under one or more -## contributor license agreements. See the NOTICE file distributed with -## this work for additional information regarding copyright ownership. -## The ASF licenses this file to You under the Apache License, Version 2.0 -## (the "License"); you may not use this file except in compliance with -## the License. You may obtain a copy of the License at -## -## http://www.apache.org/licenses/LICENSE-2.0 -## -## Unless required by applicable law or agreed to in writing, software -## distributed under the License is distributed on an "AS IS" BASIS, -## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -## See the License for the specific language governing permissions and -## limitations under the License. -## --------------------------------------------------------------------------- -# START SNIPPET: example -useJmx = false -persistent = false -brokerName = Cheese -# END SNIPPET: example \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/config.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/config.xml deleted file mode 100644 index 9ec13ffbf4..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/config.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/example.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/example.xml deleted file mode 100644 index 0a7a686435..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/example.xml +++ /dev/null @@ -1,104 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/sample-conf/connector-properties.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/sample-conf/connector-properties.xml deleted file mode 100644 index 23f065d5c1..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/sample-conf/connector-properties.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/sample-conf/jdbc-example.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/sample-conf/jdbc-example.xml deleted file mode 100644 index bbd98ea842..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/sample-conf/jdbc-example.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/sample-conf/journal-example.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/sample-conf/journal-example.xml deleted file mode 100644 index 2a79308dcf..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/sample-conf/journal-example.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - target/test-data/testJournalConfig/journal - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/sample-conf/journaledjdbc-example.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/sample-conf/journaledjdbc-example.xml deleted file mode 100644 index 4a6a0db90c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/sample-conf/journaledjdbc-example.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/sample-conf/memory-example.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/sample-conf/memory-example.xml deleted file mode 100644 index 10b38a8f8b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/sample-conf/memory-example.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/spring-test.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/spring-test.xml deleted file mode 100644 index 0e2f1456f8..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/config/spring-test.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - vm://localhost - - - - \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/AMQ3410Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/AMQ3410Test.java deleted file mode 100644 index 52b523f53e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/AMQ3410Test.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.activemq.console.command; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.console.CommandContext; -import org.apache.activemq.console.formatter.CommandShellOutputFormatter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.support.AbstractApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class AMQ3410Test extends TestCase { - - @SuppressWarnings("unused") - private static final Logger LOG = LoggerFactory.getLogger(PurgeCommandTest.class); - private static final Collection DEFAULT_OPTIONS = Arrays.asList(new String[]{"--amqurl", "tcp://localhost:61616",}); - - private static final Collection DEFAULT_TOKENS = Arrays.asList(new String[]{"FOO.QUEUE"}); - - protected AbstractApplicationContext context; - - @Override - protected void setUp() throws Exception { - super.setUp(); - - context = createApplicationContext(); - - } - - protected AbstractApplicationContext createApplicationContext() { - return new ClassPathXmlApplicationContext("org/apache/activemq/console/command/activemq.xml"); - } - - @Override - protected void tearDown() throws Exception { - BrokerService broker = (BrokerService) context.getBean("localbroker"); - broker.stop(); - broker = (BrokerService) context.getBean("default"); - broker.stop(); - super.tearDown(); - } - - public void testNoFactorySet() throws Exception { - AmqBrowseCommand command = new AmqBrowseCommand(); - CommandContext context = new CommandContext(); - - context.setFormatter(new CommandShellOutputFormatter(System.out)); - - command.setCommandContext(context); - - List tokens = new ArrayList<>(); - tokens.addAll(DEFAULT_OPTIONS); - tokens.addAll(DEFAULT_TOKENS); - - command.execute(tokens); - assertNotNull(command.getConnectionFactory()); - assertTrue(command.getConnectionFactory() instanceof ActiveMQConnectionFactory); - } - - public void testFactorySet() throws Exception { - AmqBrowseCommand command = new AmqBrowseCommand(); - CommandContext context = new CommandContext(); - - context.setFormatter(new CommandShellOutputFormatter(System.out)); - - command.setCommandContext(context); - - List tokens = new ArrayList<>(); - tokens.addAll(DEFAULT_OPTIONS); - tokens.add("--factory"); - tokens.add(DummyConnectionFactory.class.getCanonicalName()); - tokens.addAll(DEFAULT_TOKENS); - - command.execute(tokens); - - assertNotNull(command.getConnectionFactory()); - assertTrue("wrong instance returned: " + command.getConnectionFactory().getClass().getName(), command.getConnectionFactory() instanceof DummyConnectionFactory); - } - - public void testFactorySetWrong1() throws Exception { - AmqBrowseCommand command = new AmqBrowseCommand(); - CommandContext context = new CommandContext(); - - context.setFormatter(new CommandShellOutputFormatter(System.out)); - - command.setCommandContext(context); - - List tokens = new ArrayList<>(); - tokens.addAll(DEFAULT_OPTIONS); - tokens.add("--factory"); - tokens.add("org.apache.activemq.console.command.TestAMQ3410.DoesntExistFactory"); - tokens.addAll(DEFAULT_TOKENS); - - try { - command.execute(tokens); - } catch (Throwable cause) { - while (null != cause) { - if (cause instanceof java.lang.ClassNotFoundException) - return; - cause = cause.getCause(); - } - } - assertFalse("No exception caught", true); - } - - public void testFactorySetWrong2() throws Exception { - AmqBrowseCommand command = new AmqBrowseCommand(); - CommandContext context = new CommandContext(); - - context.setFormatter(new CommandShellOutputFormatter(System.out)); - - command.setCommandContext(context); - - List tokens = new ArrayList<>(); - tokens.addAll(DEFAULT_OPTIONS); - tokens.add("--factory"); - tokens.add(InvalidConnectionFactory.class.getCanonicalName()); - tokens.addAll(DEFAULT_TOKENS); - - try { - command.execute(tokens); - } catch (Throwable e) { - Throwable cause = e; - while (null != cause) { - if (cause instanceof java.lang.NoSuchMethodException) - return; - cause = cause.getCause(); - } - assertFalse(e.toString(), true); - } - assertFalse("No exception caught", true); - } - - public void testFactorySetWrong3() throws Exception { - AmqBrowseCommand command = new AmqBrowseCommand(); - CommandContext context = new CommandContext(); - - context.setFormatter(new CommandShellOutputFormatter(System.out)); - - command.setCommandContext(context); - - List tokens = new ArrayList<>(); - tokens.addAll(DEFAULT_OPTIONS); - tokens.add("--factory"); - tokens.add("java.lang.Object"); - tokens.addAll(DEFAULT_TOKENS); - - try { - command.execute(tokens); - } catch (Throwable cause) { - while (null != cause) { - if (cause instanceof java.lang.NoSuchMethodException) - return; - cause = cause.getCause(); - } - } - assertFalse(true); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/AMQ3411Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/AMQ3411Test.java deleted file mode 100644 index 4d1650744b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/AMQ3411Test.java +++ /dev/null @@ -1,196 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.console.command; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.console.CommandContext; -import org.apache.activemq.console.formatter.CommandShellOutputFormatter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.support.AbstractApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class AMQ3411Test extends TestCase { - - @SuppressWarnings("unused") - private static final Logger LOG = LoggerFactory.getLogger(AMQ3411Test.class); - private static final Collection DEFAULT_OPTIONS = Arrays.asList(new String[]{"--amqurl", "tcp://localhost:61616",}); - - private static final Collection DEFAULT_TOKENS = Arrays.asList(new String[]{"FOO.QUEUE"}); - protected AbstractApplicationContext context; - protected static final String origPassword = "ABCDEFG"; - - @Override - protected void setUp() throws Exception { - super.setUp(); - - context = createApplicationContext(); - - } - - protected AbstractApplicationContext createApplicationContext() { - return new ClassPathXmlApplicationContext("org/apache/activemq/console/command/activemq.xml"); - } - - @Override - protected void tearDown() throws Exception { - BrokerService broker = (BrokerService) context.getBean("localbroker"); - broker.stop(); - broker = (BrokerService) context.getBean("default"); - broker.stop(); - super.tearDown(); - } - - public void testNoFactorySet() throws Exception { - AmqBrowseCommand command = new AmqBrowseCommand(); - CommandContext context = new CommandContext(); - - context.setFormatter(new CommandShellOutputFormatter(System.out)); - - command.setCommandContext(context); - - List tokens = new ArrayList<>(); - tokens.addAll(DEFAULT_OPTIONS); - tokens.addAll(DEFAULT_TOKENS); - - command.execute(tokens); - - assertNotNull(command.getPasswordFactory()); - assertTrue(command.getPasswordFactory() instanceof DefaultPasswordFactory); - assertNull(command.getPassword()); - } - - public void testUsernamePasswordSet() throws Exception { - AmqBrowseCommand command = new AmqBrowseCommand(); - CommandContext context = new CommandContext(); - - String username = "user"; - String password = "password"; - - context.setFormatter(new CommandShellOutputFormatter(System.out)); - - command.setCommandContext(context); - - List tokens = new ArrayList<>(); - tokens.addAll(DEFAULT_OPTIONS); - tokens.add("--password"); - tokens.add(password); - - tokens.add("--user"); - tokens.add(username); - tokens.addAll(DEFAULT_TOKENS); - - command.execute(tokens); - - assertNotNull(command.getPasswordFactory()); - assertTrue(command.getPasswordFactory() instanceof DefaultPasswordFactory); - assertEquals(password, command.getPassword()); - assertEquals(username, command.getUsername()); - } - - public void testFactorySet() throws Exception { - AmqBrowseCommand command = new AmqBrowseCommand(); - CommandContext context = new CommandContext(); - - context.setFormatter(new CommandShellOutputFormatter(System.out)); - - command.setCommandContext(context); - - List tokens = new ArrayList<>(); - tokens.addAll(DEFAULT_OPTIONS); - tokens.add("--passwordFactory"); - tokens.add(LowercasingPasswordFactory.class.getCanonicalName()); - tokens.add("--password"); - tokens.add(origPassword); - tokens.addAll(DEFAULT_TOKENS); - - command.execute(tokens); - assertNotNull(command.getPasswordFactory()); - assertTrue(command.getPasswordFactory() instanceof LowercasingPasswordFactory); - - // validate that the factory is indeed being used for the password. - assertEquals(origPassword.toLowerCase(), command.getPassword()); - } - - public void testFactorySetWrong1() throws Exception { - AmqBrowseCommand command = new AmqBrowseCommand(); - CommandContext context = new CommandContext(); - - context.setFormatter(new CommandShellOutputFormatter(System.out)); - - command.setCommandContext(context); - - List tokens = new ArrayList<>(); - tokens.addAll(DEFAULT_OPTIONS); - tokens.add("--passwordFactory"); - tokens.add("org.apache.activemq.console.command.TestAMQ3411.DoesntExistFactory"); - tokens.add("--password"); - tokens.add(origPassword); - - tokens.addAll(DEFAULT_TOKENS); - - try { - command.execute(tokens); - } catch (Throwable e) { - Throwable cause = e; - while (null != cause) { - if (cause instanceof java.lang.ClassNotFoundException) - return; - cause = cause.getCause(); - } - assertFalse(e.toString(), true); - } - assertFalse("No exception caught", true); - } - - public void testFactorySetWrong2() throws Exception { - AmqBrowseCommand command = new AmqBrowseCommand(); - CommandContext context = new CommandContext(); - - context.setFormatter(new CommandShellOutputFormatter(System.out)); - - command.setCommandContext(context); - - List tokens = new ArrayList<>(); - tokens.addAll(DEFAULT_OPTIONS); - tokens.add("--passwordFactory"); - tokens.add("java.lang.Object"); - tokens.add("--password"); - tokens.add(origPassword); - tokens.addAll(DEFAULT_TOKENS); - - try { - command.execute(tokens); - } catch (Throwable e) { - Throwable cause = e; - while (null != cause) { - if (cause instanceof java.lang.ClassCastException) - return; - cause = cause.getCause(); - } - assertFalse(e.toString(), true); - } - assertFalse("No exception caught", true); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/DummyConnectionFactory.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/DummyConnectionFactory.java deleted file mode 100644 index 0219436352..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/DummyConnectionFactory.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.console.command; - -import java.net.URI; - -import org.apache.activemq.ActiveMQConnectionFactory; - -public class DummyConnectionFactory extends ActiveMQConnectionFactory { - - public DummyConnectionFactory() { - super(); - } - - public DummyConnectionFactory(String userName, String password, String brokerURL) { - super(userName, password, brokerURL); - } - - public DummyConnectionFactory(String userName, String password, URI brokerURL) { - super(userName, password, brokerURL); - } - - public DummyConnectionFactory(String brokerURL) { - super(brokerURL); - } - - public DummyConnectionFactory(URI brokerURL) { - super(brokerURL); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/InvalidConnectionFactory.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/InvalidConnectionFactory.java deleted file mode 100644 index 3e5d2126d8..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/InvalidConnectionFactory.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.console.command; - -import org.apache.activemq.ActiveMQConnectionFactory; - -public class InvalidConnectionFactory extends ActiveMQConnectionFactory { - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/LowercasingPasswordFactory.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/LowercasingPasswordFactory.java deleted file mode 100644 index 7219be2752..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/LowercasingPasswordFactory.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.activemq.console.command; - -public class LowercasingPasswordFactory implements PasswordFactory { - - @Override - public String getPassword(String password) { - return password.toLowerCase(); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/PurgeCommandTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/PurgeCommandTest.java deleted file mode 100644 index f41f614a4c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/PurgeCommandTest.java +++ /dev/null @@ -1,427 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.console.command; - -import javax.jms.JMSException; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.QueueBrowser; -import javax.jms.QueueConnection; -import javax.jms.QueueRequestor; -import javax.jms.QueueSession; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.management.MBeanServerConnection; -import javax.management.MBeanServerInvocationHandler; -import javax.management.ObjectInstance; -import javax.management.ObjectName; -import java.io.IOException; -import java.lang.management.ManagementFactory; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.jmx.QueueViewMBean; -import org.apache.activemq.console.CommandContext; -import org.apache.activemq.console.formatter.CommandShellOutputFormatter; -import org.apache.activemq.console.util.JmxMBeansUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.support.AbstractApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class PurgeCommandTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(PurgeCommandTest.class); - - protected static final int MESSAGE_COUNT = 10; - protected static final String PROPERTY_NAME = "XTestProperty"; - protected static final String PROPERTY_VALUE = "1:1"; - - // check for existence of property - protected static final String MSG_SEL_WITH_PROPERTY = PROPERTY_NAME + " is not null"; - - // check for non-existence of property - protected static final String MSG_SEL_WITHOUT_PROPERTY = PROPERTY_NAME + " is null"; - - // complex message selector query using XTestProperty and JMSPriority - protected static final String MSG_SEL_COMPLEX = PROPERTY_NAME + "='" + - "1:1" + "',JMSPriority>3"; - - // complex message selector query using XTestProperty AND JMSPriority - // but in SQL-92 syntax - protected static final String MSG_SEL_COMPLEX_SQL_AND = "(" + PROPERTY_NAME + "='" + - "1:1" + "') AND (JMSPriority>3)"; - - // complex message selector query using XTestProperty OR JMSPriority - // but in SQL-92 syntax - protected static final String MSG_SEL_COMPLEX_SQL_OR = "(" + PROPERTY_NAME + "='" + - "1:1" + "') OR (JMSPriority>3)"; - - protected static final String QUEUE_NAME = "org.apache.activemq.network.jms.QueueBridgeTest"; - - protected AbstractApplicationContext context; - protected QueueConnection localConnection; - protected QueueRequestor requestor; - protected QueueSession requestServerSession; - protected MessageConsumer requestServerConsumer; - protected MessageProducer requestServerProducer; - protected Queue theQueue; - - @Override - protected void setUp() throws Exception { - super.setUp(); - - context = createApplicationContext(); - - createConnections(); - - requestServerSession = localConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); - theQueue = requestServerSession.createQueue(QUEUE_NAME); - requestServerConsumer = requestServerSession.createConsumer(theQueue); - requestServerProducer = requestServerSession.createProducer(null); - - QueueSession session = localConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); - requestor = new QueueRequestor(session, theQueue); - } - - protected void createConnections() throws JMSException { - ActiveMQConnectionFactory fac = (ActiveMQConnectionFactory) context.getBean("localFactory"); - localConnection = fac.createQueueConnection(); - localConnection.start(); - } - - protected AbstractApplicationContext createApplicationContext() { - return new ClassPathXmlApplicationContext("org/apache/activemq/console/command/activemq.xml"); - } - - @Override - protected void tearDown() throws Exception { - localConnection.close(); - BrokerService broker = (BrokerService) context.getBean("localbroker"); - broker.stop(); - broker = (BrokerService) context.getBean("default"); - broker.stop(); - super.tearDown(); - } - - public int getMessageCount(QueueBrowser browser, String prefix) throws JMSException { - Enumeration e = browser.getEnumeration(); - int with = 0; - while (e.hasMoreElements()) { - Object o = e.nextElement(); - System.out.println(prefix + o); - with++; - } - return with; - } - - public void cleanup() throws JMSException { - for (int i = 0; i < MESSAGE_COUNT * 2; i++) { - requestServerConsumer.receive(); - } - } - - protected MBeanServerConnection createJmxConnection() throws IOException { - return ManagementFactory.getPlatformMBeanServer(); - } - - public void purgeAllMessages() throws IOException, Exception { - List queueList = JmxMBeansUtil.queryMBeans(createJmxConnection(), "type=Broker,brokerName=localbroker,destinationType=Queue,destinationName=*"); - for (ObjectInstance oi : queueList) { - ObjectName queueName = oi.getObjectName(); - LOG.info("Purging all messages in queue: " + queueName.getKeyProperty("Destination")); - createJmxConnection().invoke(queueName, "purge", new Object[]{}, new String[]{}); - } - } - - public void addMessages() throws IOException, Exception { - // first clean out any messages that may exist. - purgeAllMessages(); - - for (int i = 0; i < MESSAGE_COUNT; i++) { - TextMessage msg = requestServerSession.createTextMessage("test msg: " + i); - msg.setStringProperty(PROPERTY_NAME, PROPERTY_VALUE); - requestServerProducer.send(theQueue, msg); - } - for (int i = 0; i < MESSAGE_COUNT; i++) { - TextMessage msg = requestServerSession.createTextMessage("test msg: " + i); - requestServerProducer.send(theQueue, msg); - } - - } - - public void validateCounts(int expectedWithCount, - int expectedWithoutCount, - int expectedAllCount) throws JMSException { - QueueBrowser withPropertyBrowser = requestServerSession.createBrowser(theQueue, MSG_SEL_WITH_PROPERTY); - QueueBrowser withoutPropertyBrowser = requestServerSession.createBrowser(theQueue, MSG_SEL_WITHOUT_PROPERTY); - QueueBrowser allBrowser = requestServerSession.createBrowser(theQueue); - - int withCount = getMessageCount(withPropertyBrowser, "withProperty "); - int withoutCount = getMessageCount(withoutPropertyBrowser, "withoutProperty "); - int allCount = getMessageCount(allBrowser, "allMessages "); - - withPropertyBrowser.close(); - withoutPropertyBrowser.close(); - allBrowser.close(); - - assertEquals("Expected withCount to be " + expectedWithCount + " was " + withCount, expectedWithCount, withCount); - assertEquals("Expected withoutCount to be " + expectedWithoutCount + " was " + withoutCount, expectedWithoutCount, withoutCount); - assertEquals("Expected allCount to be " + expectedAllCount + " was " + allCount, expectedAllCount, allCount); - LOG.info("withCount = " + withCount + "\n withoutCount = " + withoutCount + "\n allCount = " + allCount + "\n = " + "\n"); - } - - /** - * This test ensures that the queueViewMbean will work. - * - * @throws Exception - */ - public void testQueueViewMbean() throws Exception { - - try { - addMessages(); - - validateCounts(MESSAGE_COUNT, MESSAGE_COUNT, MESSAGE_COUNT * 2); - - List tokens = Arrays.asList(new String[]{"*"}); - for (String token : tokens) { - List queueList = JmxMBeansUtil.queryMBeans(createJmxConnection(), "type=Broker,brokerName=localbroker,destinationType=Queue,destinationName=" + token); - - for (ObjectInstance queue : queueList) { - ObjectName queueName = queue.getObjectName(); - QueueViewMBean proxy = MBeanServerInvocationHandler.newProxyInstance(createJmxConnection(), queueName, QueueViewMBean.class, true); - int removed = proxy.removeMatchingMessages(MSG_SEL_WITH_PROPERTY); - LOG.info("Removed: " + removed); - } - } - - validateCounts(0, MESSAGE_COUNT, MESSAGE_COUNT); - - } finally { - purgeAllMessages(); - } - } - - public void testPurgeCommandSimpleSelector() throws Exception { - try { - PurgeCommand purgeCommand = new PurgeCommand(); - CommandContext context = new CommandContext(); - - context.setFormatter(new CommandShellOutputFormatter(System.out)); - - purgeCommand.setCommandContext(context); - purgeCommand.setJmxUseLocal(true); - - List tokens = new ArrayList<>(); - tokens.add("--msgsel"); - tokens.add(MSG_SEL_WITH_PROPERTY); - - addMessages(); - validateCounts(MESSAGE_COUNT, MESSAGE_COUNT, MESSAGE_COUNT * 2); - - purgeCommand.execute(tokens); - - validateCounts(0, MESSAGE_COUNT, MESSAGE_COUNT); - } finally { - purgeAllMessages(); - } - } - - public void testPurgeCommandComplexSelector() throws Exception { - try { - PurgeCommand purgeCommand = new PurgeCommand(); - CommandContext context = new CommandContext(); - - context.setFormatter(new CommandShellOutputFormatter(System.out)); - - purgeCommand.setCommandContext(context); - purgeCommand.setJmxUseLocal(true); - - List tokens = new ArrayList<>(); - tokens.add("--msgsel"); - tokens.add(MSG_SEL_COMPLEX); - - addMessages(); - validateCounts(MESSAGE_COUNT, MESSAGE_COUNT, MESSAGE_COUNT * 2); - - purgeCommand.execute(tokens); - - QueueBrowser withPropertyBrowser = requestServerSession.createBrowser(theQueue, MSG_SEL_COMPLEX); - QueueBrowser allBrowser = requestServerSession.createBrowser(theQueue); - - int withCount = getMessageCount(withPropertyBrowser, "withProperty "); - int allCount = getMessageCount(allBrowser, "allMessages "); - - withPropertyBrowser.close(); - allBrowser.close(); - - assertEquals("Expected withCount to be " + "0" + " was " + withCount, 0, withCount); - assertEquals("Expected allCount to be " + MESSAGE_COUNT + " was " + allCount, MESSAGE_COUNT, allCount); - LOG.info("withCount = " + withCount + "\n allCount = " + - allCount + "\n = " + "\n"); - } finally { - purgeAllMessages(); - } - } - - public void testPurgeCommandComplexSQLSelector_AND() throws Exception { - try { - - String one = "ID:mac.fritz.box:1213242.3231.1:1:1:100"; - String two = "\\*:100"; - try { - if (one.matches(two)) - LOG.info("String matches."); - else - LOG.info("string does not match."); - } catch (Exception ex) { - LOG.error(ex.getMessage()); - } - - PurgeCommand purgeCommand = new PurgeCommand(); - CommandContext context = new CommandContext(); - - context.setFormatter(new CommandShellOutputFormatter(System.out)); - - purgeCommand.setCommandContext(context); - purgeCommand.setJmxUseLocal(true); - - List tokens = new ArrayList<>(); - tokens.add("--msgsel"); - tokens.add(MSG_SEL_COMPLEX_SQL_AND); - - addMessages(); - validateCounts(MESSAGE_COUNT, MESSAGE_COUNT, MESSAGE_COUNT * 2); - - purgeCommand.execute(tokens); - - QueueBrowser withPropertyBrowser = requestServerSession.createBrowser(theQueue, MSG_SEL_COMPLEX_SQL_AND); - QueueBrowser allBrowser = requestServerSession.createBrowser(theQueue); - - int withCount = getMessageCount(withPropertyBrowser, "withProperty "); - int allCount = getMessageCount(allBrowser, "allMessages "); - - withPropertyBrowser.close(); - allBrowser.close(); - - assertEquals("Expected withCount to be " + "0" + " was " + withCount, 0, withCount); - assertEquals("Expected allCount to be " + MESSAGE_COUNT + " was " + allCount, MESSAGE_COUNT, allCount); - LOG.info("withCount = " + withCount + "\n allCount = " + - allCount + "\n = " + "\n"); - } finally { - purgeAllMessages(); - } - } - - public void testPurgeCommandComplexSQLSelector_OR() throws Exception { - try { - PurgeCommand purgeCommand = new PurgeCommand(); - CommandContext context = new CommandContext(); - - context.setFormatter(new CommandShellOutputFormatter(System.out)); - - purgeCommand.setCommandContext(context); - purgeCommand.setJmxUseLocal(true); - - List tokens = new ArrayList<>(); - tokens.add("--msgsel"); - tokens.add(MSG_SEL_COMPLEX_SQL_OR); - - addMessages(); - validateCounts(MESSAGE_COUNT, MESSAGE_COUNT, MESSAGE_COUNT * 2); - - purgeCommand.execute(tokens); - - QueueBrowser withPropertyBrowser = requestServerSession.createBrowser(theQueue, MSG_SEL_COMPLEX_SQL_OR); - QueueBrowser allBrowser = requestServerSession.createBrowser(theQueue); - - int withCount = getMessageCount(withPropertyBrowser, "withProperty "); - int allCount = getMessageCount(allBrowser, "allMessages "); - - withPropertyBrowser.close(); - allBrowser.close(); - - assertEquals("Expected withCount to be 0 but was " + withCount, 0, withCount); - assertEquals("Expected allCount to be 0 but was " + allCount, 0, allCount); - LOG.info("withCount = " + withCount + "\n allCount = " + - allCount + "\n = " + "\n"); - } finally { - purgeAllMessages(); - } - } - - public void testDummy() throws Exception { - try { - - String one = "ID:mac.fritz.box:1213242.3231.1:1:1:100"; - String two = "ID*:100"; - try { - if (one.matches(two)) - LOG.info("String matches."); - else - LOG.info("string does not match."); - } catch (Exception ex) { - LOG.error(ex.getMessage()); - } - - PurgeCommand purgeCommand = new PurgeCommand(); - CommandContext context = new CommandContext(); - - context.setFormatter(new CommandShellOutputFormatter(System.out)); - - purgeCommand.setCommandContext(context); - purgeCommand.setJmxUseLocal(true); - - List tokens = new ArrayList<>(); - tokens.add("--msgsel"); - tokens.add("(XTestProperty LIKE '1:*') AND (JMSPriority>3)"); - - addMessages(); - - purgeCommand.execute(tokens); - - /* - QueueBrowser withPropertyBrowser = requestServerSession.createBrowser( - theQueue, MSG_SEL_COMPLEX_SQL_AND); - QueueBrowser allBrowser = requestServerSession.createBrowser(theQueue); - - int withCount = getMessageCount(withPropertyBrowser, "withProperty "); - int allCount = getMessageCount(allBrowser, "allMessages "); - - withPropertyBrowser.close(); - allBrowser.close(); - - assertEquals("Expected withCount to be " + "0" + " was " - + withCount, 0, withCount); - assertEquals("Expected allCount to be " + MESSAGE_COUNT + " was " - + allCount, MESSAGE_COUNT, allCount); - LOG.info("withCount = " + withCount + "\n allCount = " + - allCount + "\n = " + "\n"); - */ - } finally { - purgeAllMessages(); - } - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/activemq.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/activemq.xml deleted file mode 100644 index b2aaf16a09..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/console/command/activemq.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - tcp://localhost:61234 - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationFilterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationFilterTest.java deleted file mode 100644 index 98126f6777..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationFilterTest.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.activemq.filter; - -import junit.framework.TestCase; - -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; - -public class DestinationFilterTest extends TestCase { - - public void testPrefixFilter() throws Exception { - DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue(">")); - assertTrue("Filter not parsed well: " + filter.getClass(), filter instanceof PrefixDestinationFilter); - System.out.println(filter); - assertFalse("Filter matched wrong destination type", filter.matches(new ActiveMQTopic(">"))); - } - - public void testWildcardFilter() throws Exception { - DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.*")); - assertTrue("Filter not parsed well: " + filter.getClass(), filter instanceof WildcardDestinationFilter); - assertFalse("Filter matched wrong destination type", filter.matches(new ActiveMQTopic("A.B"))); - } - - public void testCompositeFilter() throws Exception { - DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.B,B.C")); - assertTrue("Filter not parsed well: " + filter.getClass(), filter instanceof CompositeDestinationFilter); - assertFalse("Filter matched wrong destination type", filter.matches(new ActiveMQTopic("A.B"))); - } - - public void testMatchesChild() throws Exception { - DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.*.C")); - assertFalse("Filter matched wrong destination type", filter.matches(new ActiveMQTopic("A.B"))); - assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.B.C"))); - - filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.*")); - assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.B"))); - assertFalse("Filter did match", filter.matches(new ActiveMQQueue("A"))); - } - - public void testMatchesAny() throws Exception { - DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.>.>")); - - assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.C"))); - - assertFalse("Filter did match", filter.matches(new ActiveMQQueue("B"))); - assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.B"))); - assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.B.C.D.E.F"))); - assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A"))); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapMemoryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapMemoryTest.java deleted file mode 100644 index 0da8c0d693..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapMemoryTest.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.activemq.filter; - -import junit.framework.TestCase; - -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQTopic; - -public class DestinationMapMemoryTest extends TestCase { - - public void testLongDestinationPath() throws Exception { - ActiveMQTopic d1 = new ActiveMQTopic("1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18"); - DestinationMap map = new DestinationMap(); - map.put(d1, d1); - } - - public void testVeryLongestinationPaths() throws Exception { - - for (int i = 1; i < 100; i++) { - String name = "1"; - for (int j = 2; j <= i; j++) { - name += "." + j; - } - // System.out.println("Checking: " + name); - try { - ActiveMQDestination d1 = createDestination(name); - DestinationMap map = new DestinationMap(); - map.put(d1, d1); - } catch (Throwable e) { - fail("Destination name too long: " + name + " : " + e); - } - } - } - - protected ActiveMQDestination createDestination(String name) { - return new ActiveMQTopic(name); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapTempDestinationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapTempDestinationTest.java deleted file mode 100644 index 8d64e8b9c5..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapTempDestinationTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.filter; - -import java.util.Set; - -import junit.framework.TestCase; - -import org.apache.activemq.command.ActiveMQTempQueue; -import org.apache.activemq.command.ConnectionId; -import org.apache.activemq.util.IdGenerator; - -public class DestinationMapTempDestinationTest extends TestCase { - - public void testtestTempDestinations() throws Exception { - ConnectionId id = new ConnectionId(new IdGenerator().generateId()); - DestinationMap map = new DestinationMap(); - Object value = new Object(); - int count = 1000; - for (int i = 0; i < count; i++) { - ActiveMQTempQueue queue = new ActiveMQTempQueue(id, i); - map.put(queue, value); - } - for (int i = 0; i < count; i++) { - ActiveMQTempQueue queue = new ActiveMQTempQueue(id, i); - map.remove(queue, value); - Set set = map.get(queue); - assertTrue(set.isEmpty()); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapTest.java deleted file mode 100644 index 4b80ac1739..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationMapTest.java +++ /dev/null @@ -1,431 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.filter; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Set; - -import junit.framework.TestCase; - -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; - -public class DestinationMapTest extends TestCase { - - protected DestinationMap map = new DestinationMap(); - - protected ActiveMQDestination d1 = createDestination("TEST.D1"); - protected ActiveMQDestination d2 = createDestination("TEST.BAR.D2"); - protected ActiveMQDestination d3 = createDestination("TEST.BAR.D3"); - protected ActiveMQDestination compositeDestination1 = createDestination("TEST.D1,TEST.BAR.D2"); - protected ActiveMQDestination compositeDestination2 = createDestination("TEST.D1,TEST.BAR.D3"); - - protected Object v1 = "value1"; - protected Object v2 = "value2"; - protected Object v3 = "value3"; - protected Object v4 = "value4"; - protected Object v5 = "value5"; - protected Object v6 = "value6"; - - public void testCompositeDestinations() throws Exception { - ActiveMQDestination d1 = createDestination("TEST.BAR.D2"); - ActiveMQDestination d2 = createDestination("TEST.BAR.D3"); - map.put(d1, d1); - map.put(d2, d2); - map.get(createDestination("TEST.BAR.D2,TEST.BAR.D3")); - } - - public void testSimpleDestinations() throws Exception { - map.put(d1, v1); - map.put(d2, v2); - map.put(d3, v3); - - assertMapValue(d1, v1); - assertMapValue(d2, v2); - assertMapValue(d3, v3); - } - - public void testQueueAndTopicWithSameName() throws Exception { - ActiveMQQueue q1 = new ActiveMQQueue("foo"); - ActiveMQTopic t1 = new ActiveMQTopic("foo"); - - map.put(q1, v1); - map.put(t1, v2); - - assertMapValue(q1, v1); - assertMapValue(t1, v2); - } - - public void testSimpleDestinationsWithMultipleValues() throws Exception { - map.put(d1, v1); - map.put(d2, v2); - map.put(d2, v3); - - assertMapValue(d1, v1); - assertMapValue("TEST.BAR.D2", v2, v3); - assertMapValue(d3, null); - } - - public void testSimpleAndCompositeDestinations() throws Exception { - map.put(d1, v1); - map.put(compositeDestination1, v2); - map.put(compositeDestination2, v3); - - assertMapValue("TEST.D1", v1, v2, v3); - assertMapValue(d2, v2); - assertMapValue(d3, v3); - assertMapValue(compositeDestination1.toString(), v1, v2, v3); - assertMapValue(compositeDestination2.toString(), v1, v2, v3); - - map.remove(compositeDestination1, v2); - map.remove(compositeDestination2, v3); - - assertMapValue("TEST.D1", v1); - } - - public void testLookupOneStepWildcardDestinations() throws Exception { - map.put(d1, v1); - map.put(d2, v2); - map.put(d3, v3); - - assertMapValue("TEST.D1", v1); - assertMapValue("TEST.*", v1); - assertMapValue("*.D1", v1); - assertMapValue("*.*", v1); - - assertMapValue("TEST.BAR.D2", v2); - assertMapValue("TEST.*.D2", v2); - assertMapValue("*.BAR.D2", v2); - assertMapValue("*.*.D2", v2); - - assertMapValue("TEST.BAR.D3", v3); - assertMapValue("TEST.*.D3", v3); - assertMapValue("*.BAR.D3", v3); - assertMapValue("*.*.D3", v3); - - assertMapValue("TEST.BAR.D4", null); - - assertMapValue("TEST.BAR.*", v2, v3); - } - - public void testLookupMultiStepWildcardDestinations() throws Exception { - map.put(d1, v1); - map.put(d2, v2); - map.put(d3, v3); - - List allValues = Arrays.asList(new Object[]{v1, v2, v3}); - - assertMapValue(">", allValues); - assertMapValue("TEST.>", allValues); - assertMapValue("*.>", allValues); - assertMapValue("TEST.*.>", allValues); - assertMapValue("TEST.*.*.>", v2, v3); - - assertMapValue("FOO.>", null); - } - - public void testStoreWildcardWithOneStepPath() throws Exception { - put("TEST.*", v1); - put("TEST.D1", v2); - put("TEST.BAR.*", v2); - put("TEST.BAR.D3", v3); - - assertMapValue("FOO", null); - assertMapValue("TEST.FOO", v1); - assertMapValue("TEST.D1", v1, v2); - - assertMapValue("TEST.FOO.FOO", null); - assertMapValue("TEST.BAR.FOO", v2); - assertMapValue("TEST.BAR.D3", v2, v3); - - assertMapValue("TEST.*", v1, v2); - assertMapValue("*.D1", v1, v2); - assertMapValue("*.*", v1, v2); - assertMapValue("TEST.*.*", v2, v3); - assertMapValue("TEST.BAR.*", v2, v3); - assertMapValue("*.*.*", v2, v3); - assertMapValue("*.BAR.*", v2, v3); - assertMapValue("*.BAR.D3", v2, v3); - assertMapValue("*.*.D3", v2, v3); - } - - public void testStoreWildcardInMiddleOfPath() throws Exception { - put("TEST.*", v1); - put("TEST.D1", v2); - put("TEST.BAR.*", v2); - put("TEST.XYZ.D3", v3); - put("TEST.XYZ.D4", v4); - put("TEST.BAR.D3", v5); - put("TEST.*.D2", v6); - - assertMapValue("TEST.*.D3", v2, v3, v5); - assertMapValue("TEST.*.D4", v2, v4); - - assertMapValue("TEST.*", v1, v2); - assertMapValue("TEST.*.*", v2, v3, v4, v5, v6); - assertMapValue("TEST.*.>", v1, v2, v3, v4, v5, v6); - assertMapValue("TEST.>", v1, v2, v3, v4, v5, v6); - assertMapValue("TEST.>.>", v1, v2, v3, v4, v5, v6); - assertMapValue("*.*.D3", v2, v3, v5); - assertMapValue("TEST.BAR.*", v2, v5, v6); - - assertMapValue("TEST.BAR.D2", v2, v6); - assertMapValue("TEST.*.D2", v2, v6); - assertMapValue("TEST.BAR.*", v2, v5, v6); - } - - public void testDoubleWildcardDoesNotMatchLongerPattern() throws Exception { - put("TEST.*", v1); - put("TEST.BAR.D3", v2); - - assertMapValue("*.*.D3", v2); - } - - public void testWildcardAtEndOfPathAndAtBeginningOfSearch() throws Exception { - put("TEST.*", v1); - - assertMapValue("*.D1", v1); - } - - public void testAnyPathWildcardInMap() throws Exception { - put("TEST.FOO.>", v1); - - assertMapValue("TEST.FOO.BAR.WHANOT.A.B.C", v1); - assertMapValue("TEST.FOO.BAR.WHANOT", v1); - assertMapValue("TEST.FOO.BAR", v1); - - assertMapValue("TEST.*.*", v1); - assertMapValue("TEST.BAR", null); - - assertMapValue("TEST.FOO", v1); - } - - public void testSimpleAddRemove() throws Exception { - put("TEST.D1", v2); - - assertEquals("Root child count", 1, map.getTopicRootChildCount()); - - assertMapValue("TEST.D1", v2); - - remove("TEST.D1", v2); - - assertEquals("Root child count", 0, map.getTopicRootChildCount()); - assertMapValue("TEST.D1", null); - } - - public void testMQTTMappedWildcards() throws Exception { - put("TopicA", v1); - put(".TopicA", v2); - put("TopicA.", v3); - put(".", v4); - put("..TopicA", v5); - put("..", v6); - - // test wildcard patterns "#", "+", "+/#", "/+", "+/", "+/+", "+/+/", "+/+/+" - assertMapValue(">", v1, v2, v3, v4, v5, v6); - assertMapValue("*", v1); - assertMapValue("*.>", v1, v2, v3, v4, v5, v6); - assertMapValue(".*", v2, v4); - assertMapValue("*.", v3, v4); - assertMapValue("*.*", v2, v3, v4); - assertMapValue("*.*.", v6); - assertMapValue("*.*.*", v5, v6); - } - - public void testStoreAndLookupAllWildcards() throws Exception { - loadSample2(); - - assertSample2(); - - // lets remove everything and add it back - remove("TEST.FOO", v1); - - assertMapValue("TEST.FOO", v2, v3, v4); - assertMapValue("TEST.*", v2, v3, v4, v6); - assertMapValue("*.*", v2, v3, v4, v6); - - remove("TEST.XYZ", v6); - - assertMapValue("TEST.*", v2, v3, v4); - assertMapValue("*.*", v2, v3, v4); - - remove("TEST.*", v2); - - assertMapValue("TEST.*", v3, v4); - assertMapValue("*.*", v3, v4); - - remove(">", v4); - - assertMapValue("TEST.*", v3); - assertMapValue("*.*", v3); - - remove("TEST.>", v3); - remove("TEST.FOO.BAR", v5); - - assertMapValue("FOO", null); - assertMapValue("TEST.FOO", null); - assertMapValue("TEST.D1", null); - - assertMapValue("TEST.FOO.FOO", null); - assertMapValue("TEST.BAR.FOO", null); - assertMapValue("TEST.FOO.BAR", null); - assertMapValue("TEST.BAR.D3", null); - - assertMapValue("TEST.*", null); - assertMapValue("*.*", null); - assertMapValue("*.D1", null); - assertMapValue("TEST.*.*", null); - assertMapValue("TEST.BAR.*", null); - - loadSample2(); - - assertSample2(); - - remove(">", v4); - remove("TEST.*", v2); - - assertMapValue("FOO", null); - assertMapValue("TEST.FOO", v1, v3); - assertMapValue("TEST.D1", v3); - - assertMapValue("TEST.FOO.FOO", v3); - assertMapValue("TEST.BAR.FOO", v3); - assertMapValue("TEST.FOO.BAR", v3, v5); - assertMapValue("TEST.BAR.D3", v3); - - assertMapValue("TEST.*", v1, v3, v6); - assertMapValue("*.*", v1, v3, v6); - assertMapValue("*.D1", v3); - assertMapValue("TEST.*.*", v3, v5); - assertMapValue("TEST.BAR.*", v3); - } - - public void testAddAndRemove() throws Exception { - - put("FOO.A", v1); - assertMapValue("FOO.>", v1); - - put("FOO.B", v2); - assertMapValue("FOO.>", v1, v2); - - map.removeAll(createDestination("FOO.A")); - - assertMapValue("FOO.>", v2); - } - - protected void loadSample2() { - put("TEST.FOO", v1); - put("TEST.*", v2); - put("TEST.>", v3); - put(">", v4); - put("TEST.FOO.BAR", v5); - put("TEST.XYZ", v6); - } - - protected void assertSample2() { - assertMapValue("FOO", v4); - assertMapValue("TEST.FOO", v1, v2, v3, v4); - assertMapValue("TEST.D1", v2, v3, v4); - - assertMapValue("TEST.FOO.FOO", v3, v4); - assertMapValue("TEST.BAR.FOO", v3, v4); - assertMapValue("TEST.FOO.BAR", v3, v4, v5); - assertMapValue("TEST.BAR.D3", v3, v4); - - assertMapValue("TEST.*", v1, v2, v3, v4, v6); - assertMapValue("*.*", v1, v2, v3, v4, v6); - assertMapValue("*.D1", v2, v3, v4); - assertMapValue("TEST.*.*", v3, v4, v5); - assertMapValue("TEST.BAR.*", v3, v4); - } - - protected void put(String name, Object value) { - map.put(createDestination(name), value); - } - - protected void remove(String name, Object value) { - ActiveMQDestination destination = createDestination(name); - map.remove(destination, value); - } - - protected void assertMapValue(String destinationName, Object expected) { - ActiveMQDestination destination = createDestination(destinationName); - assertMapValue(destination, expected); - } - - protected void assertMapValue(String destinationName, Object expected1, Object expected2) { - assertMapValue(destinationName, Arrays.asList(new Object[]{expected1, expected2})); - } - - protected void assertMapValue(String destinationName, Object expected1, Object expected2, Object expected3) { - assertMapValue(destinationName, Arrays.asList(new Object[]{expected1, expected2, expected3})); - } - - protected void assertMapValue(String destinationName, - Object expected1, - Object expected2, - Object expected3, - Object expected4) { - assertMapValue(destinationName, Arrays.asList(new Object[]{expected1, expected2, expected3, expected4})); - } - - protected void assertMapValue(String destinationName, - Object expected1, - Object expected2, - Object expected3, - Object expected4, - Object expected5) { - assertMapValue(destinationName, Arrays.asList(new Object[]{expected1, expected2, expected3, expected4, expected5})); - } - - protected void assertMapValue(String destinationName, - Object expected1, - Object expected2, - Object expected3, - Object expected4, - Object expected5, - Object expected6) { - assertMapValue(destinationName, Arrays.asList(new Object[]{expected1, expected2, expected3, expected4, expected5, expected6})); - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - protected void assertMapValue(ActiveMQDestination destination, Object expected) { - List expectedList = null; - if (expected == null) { - expectedList = Collections.EMPTY_LIST; - } else if (expected instanceof List) { - expectedList = (List) expected; - } else { - expectedList = new ArrayList(); - expectedList.add(expected); - } - Collections.sort(expectedList); - Set actualSet = map.get(destination); - List actual = new ArrayList(actualSet); - Collections.sort(actual); - assertEquals("map value for destinationName: " + destination, expectedList, actual); - } - - protected ActiveMQDestination createDestination(String name) { - return new ActiveMQTopic(name); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationPathTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationPathTest.java deleted file mode 100644 index 2484585e31..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationPathTest.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.activemq.filter; - -import org.apache.activemq.test.TestSupport; - -public class DestinationPathTest extends TestSupport { - - public void testPathParse() { - assertParse("FOO", new String[]{"FOO"}); - assertParse("FOO.BAR", new String[]{"FOO", "BAR"}); - assertParse("FOO.*", new String[]{"FOO", "*"}); - assertParse("FOO.>", new String[]{"FOO", ">"}); - assertParse("FOO.BAR.XYZ", new String[]{"FOO", "BAR", "XYZ"}); - assertParse("FOO.BAR.", new String[]{"FOO", "BAR", ""}); - } - - protected void assertParse(String subject, String[] expected) { - String[] path = DestinationPath.getDestinationPaths(subject); - assertArrayEqual(subject, expected, path); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicy.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicy.java deleted file mode 100644 index 9cfff27e9a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicy.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.activemq.filter; - -import java.util.List; - -/** - * Represents a destination based policy - */ -public class DummyPolicy extends DestinationMap { - - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - protected Class getEntryClass() { - return DummyPolicyEntry.class; - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void setEntries(List entries) { - super.setEntries(entries); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicyEntry.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicyEntry.java deleted file mode 100644 index ea8a871f7a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicyEntry.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.filter; - -/** - * - * - */ -public class DummyPolicyEntry extends DestinationMapEntry { - - private String description; - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @Override - public Comparable getValue() { - return description; - } - - protected String getValuePropertyName() { - return "description"; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicyTest.java deleted file mode 100644 index 14d1a02548..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DummyPolicyTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.filter; - -import java.util.Set; - -import org.apache.activemq.SpringTestSupport; -import org.apache.activemq.command.ActiveMQTopic; -import org.springframework.context.support.AbstractApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * - */ -public class DummyPolicyTest extends SpringTestSupport { - - public void testPolicy() throws Exception { - DummyPolicy policy = (DummyPolicy) getBean("policy"); - - Set set = policy.get(new ActiveMQTopic("FOO.BAR")); - - assertSetEquals("FOO.BAR set", new Object[]{"Edam", "Cheddar"}, set); - } - - @Override - protected AbstractApplicationContext createApplicationContext() { - return new ClassPathXmlApplicationContext("org/apache/activemq/filter/dummyPolicy.xml"); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/dummyPolicy.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/dummyPolicy.xml deleted file mode 100644 index 65859861b6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/dummyPolicy.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jmx/JmxCreateNCTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jmx/JmxCreateNCTest.java deleted file mode 100644 index c6738fa75d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jmx/JmxCreateNCTest.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.activemq.jmx; - -import javax.management.ObjectName; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.jmx.BrokerViewMBean; -import org.apache.activemq.broker.jmx.NetworkConnectorViewMBean; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -/** - * This test shows that when we create a network connector via JMX, - * the NC/bridge shows up in the MBean Server - * - * @author Christian Posta - */ -public class JmxCreateNCTest { - - private static final String BROKER_NAME = "jmx-broker"; - - @Test - public void testBridgeRegistration() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName(BROKER_NAME); - broker.setUseJmx(true); // explicitly set this so no funny issues - broker.start(); - broker.waitUntilStarted(); - - // now create network connector over JMX - ObjectName brokerObjectName = new ObjectName("org.apache.activemq:type=Broker,brokerName=" + BROKER_NAME); - BrokerViewMBean proxy = (BrokerViewMBean) broker.getManagementContext().newProxyInstance(brokerObjectName, BrokerViewMBean.class, true); - - assertNotNull("We could not retrieve the broker from JMX", proxy); - - // let's add the NC - String connectoName = proxy.addNetworkConnector("static:(tcp://localhost:61617)"); - assertEquals("NC", connectoName); - - // Make sure we can retrieve the NC through JMX - ObjectName networkConnectorObjectName = new ObjectName("org.apache.activemq:type=Broker,brokerName=" + BROKER_NAME + - ",connector=networkConnectors,networkConnectorName=" + connectoName); - NetworkConnectorViewMBean nc = (NetworkConnectorViewMBean) broker.getManagementContext().newProxyInstance(networkConnectorObjectName, NetworkConnectorViewMBean.class, true); - - assertNotNull(nc); - assertEquals("NC", nc.getName()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jmx/OpenTypeSupportTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jmx/OpenTypeSupportTest.java deleted file mode 100644 index 818b9f2628..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jmx/OpenTypeSupportTest.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.activemq.jmx; - -import javax.jms.BytesMessage; -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; -import javax.management.openmbean.CompositeData; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.jmx.CompositeDataConstants; -import org.apache.activemq.broker.jmx.OpenTypeSupport; -import org.apache.activemq.broker.jmx.QueueViewMBean; -import org.apache.activemq.command.ActiveMQBytesMessage; -import org.apache.activemq.command.ActiveMQQueue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; - -public class OpenTypeSupportTest { - - private static final Logger LOG = LoggerFactory.getLogger(OpenTypeSupportTest.class); - - private static BrokerService brokerService; - private static String TESTQUEUE = "testQueue"; - private static ActiveMQConnectionFactory connectionFactory; - private static String BYTESMESSAGE_TEXT = "This is a short text"; - private static String BROKER_ADDRESS = "tcp://localhost:0"; - private static ActiveMQQueue queue = new ActiveMQQueue(TESTQUEUE); - - private String connectionUri; - - @Before - public void setUp() throws Exception { - brokerService = new BrokerService(); - brokerService.setPersistent(false); - brokerService.setUseJmx(true); - connectionUri = brokerService.addConnector(BROKER_ADDRESS).getPublishableConnectString(); - brokerService.start(); - connectionFactory = new ActiveMQConnectionFactory(connectionUri); - sendMessage(); - } - - @After - public void tearDown() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } - - private static void sendMessage() throws JMSException { - Connection conn = connectionFactory.createConnection(); - try { - conn.start(); - Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination queue = session.createQueue(TESTQUEUE); - BytesMessage toSend = session.createBytesMessage(); - toSend.writeBytes(BYTESMESSAGE_TEXT.getBytes()); - MessageProducer producer = session.createProducer(queue); - producer.send(queue, toSend); - } finally { - conn.close(); - } - } - - @Test - public void bytesMessagePreview() throws Exception { - QueueViewMBean queue = getProxyToQueueViewMBean(); - assertEquals(extractText(queue.browse()[0]), extractText(queue.browse()[0])); - } - - @Test - public void testBrowseByteMessageFails() throws Exception { - ActiveMQBytesMessage bm = new ActiveMQBytesMessage(); - bm.writeBytes("123456".getBytes()); - Object result = OpenTypeSupport.convert(bm); - LOG.info("result : " + result); - } - - private String extractText(CompositeData message) { - Byte content[] = (Byte[]) message.get(CompositeDataConstants.BODY_PREVIEW); - byte out[] = new byte[content.length]; - System.arraycopy(content, 0, out, 0, content.length); - return new String(out); - } - - private QueueViewMBean getProxyToQueueViewMBean() throws MalformedObjectNameException, JMSException { - final ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + queue.getQueueName()); - QueueViewMBean proxy = (QueueViewMBean) brokerService.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); - return proxy; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ActiveMQInitialContextFactoryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ActiveMQInitialContextFactoryTest.java deleted file mode 100644 index 247b8dcada..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ActiveMQInitialContextFactoryTest.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.activemq.jndi; - -import javax.naming.InitialContext; -import javax.naming.NamingException; - -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; - -/** - * - */ -public class ActiveMQInitialContextFactoryTest extends JNDITestSupport { - - public void testConnectionFactoriesArePresent() throws NamingException { - String lookupName = getConnectionFactoryLookupName(); - assertConnectionFactoryPresent(lookupName); - } - - public void testDestinationsArePresent() throws NamingException { - - // Retrieving destinations context is not yet implemented on the broker. - // For this test, a jndi file properties will be used. - - InitialContext context = new InitialContext(); - - Object topicDestination = context.lookup("MyTopic"); - - // check if MyTopic is an ActiveMQTopic - assertTrue("Should have found a topic but found: " + topicDestination, topicDestination instanceof ActiveMQTopic); - - Object queueDestination = context.lookup("MyQueue"); - - // check if MyQueue is an ActiveMQueue - assertTrue("Should have found a queue but found: " + queueDestination, queueDestination instanceof ActiveMQQueue); - - } - - public void testDynamicallyGrowing() throws Exception { - Object answer = context.lookup("dynamicQueues/FOO.BAR"); - assertTrue("Should have found a queue but found: " + answer, answer instanceof ActiveMQQueue); - - ActiveMQQueue queue = (ActiveMQQueue) answer; - assertEquals("queue name", "FOO.BAR", queue.getPhysicalName()); - - answer = context.lookup("dynamicTopics/A.B.C"); - assertTrue("Should have found a topic but found: " + answer, answer instanceof ActiveMQTopic); - - ActiveMQTopic topic = (ActiveMQTopic) answer; - assertEquals("topic name", "A.B.C", topic.getPhysicalName()); - - } - - protected String getConnectionFactoryLookupName() { - return "ConnectionFactory"; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ActiveMQWASInitialContextFactoryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ActiveMQWASInitialContextFactoryTest.java deleted file mode 100644 index 922bd13935..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ActiveMQWASInitialContextFactoryTest.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.activemq.jndi; - -import javax.naming.Context; -import java.util.Hashtable; - -public class ActiveMQWASInitialContextFactoryTest extends JNDITestSupport { - - public void testTransformEnvironment() { - Hashtable originalEnvironment = new Hashtable<>(); - originalEnvironment.put("java.naming.connectionFactoryNames", "ConnectionFactory"); - originalEnvironment.put("java.naming.topic.jms.systemMessageTopic", "jms/systemMessageTopic"); - originalEnvironment.put(Context.PROVIDER_URL, "tcp://localhost:61616;tcp://localhost:61617"); - originalEnvironment.put("non-string", Integer.valueOf(43)); - originalEnvironment.put("java.naming.queue", "jms/systemMessageQueue"); - - Hashtable transformedEnvironment = new ActiveMQWASInitialContextFactory().transformEnvironment(originalEnvironment); - assertEquals("ConnectionFactory", "ConnectionFactory", transformedEnvironment.get("connectionFactoryNames")); - assertEquals("topic.jm", "jms/systemMessageTopic", transformedEnvironment.get("topic.jms/systemMessageTopic")); - assertEquals("java.naming.provider.url", "tcp://localhost:61616,tcp://localhost:61617", transformedEnvironment.get("java.naming.provider.url")); - assertNull("non-string", transformedEnvironment.get("non-string")); - - assertEquals("queue", "jms/systemMessageQueue", transformedEnvironment.get("java.naming.queue")); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/CustomConnectionFactoryNameTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/CustomConnectionFactoryNameTest.java deleted file mode 100644 index cf8b3c66a9..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/CustomConnectionFactoryNameTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.jndi; - -import javax.naming.NamingException; - -import org.apache.activemq.ActiveMQConnectionFactory; - -/** - * Test case for AMQ-141 - */ -public class CustomConnectionFactoryNameTest extends ActiveMQInitialContextFactoryTest { - - @Override - public void testConnectionFactoriesArePresent() throws NamingException { - super.testConnectionFactoriesArePresent(); - assertConnectionFactoryPresent("jms/Connection"); - assertConnectionFactoryPresent("jms/DURABLE_SUB_CONNECTION_FACTORY"); - } - - public void testConnectionFactoriesAreConfigured() throws NamingException { - super.testConnectionFactoriesArePresent(); - ActiveMQConnectionFactory factory1 = (ActiveMQConnectionFactory) context.lookup("jms/Connection"); - assertNull(factory1.getClientID()); - ActiveMQConnectionFactory factory2 = (ActiveMQConnectionFactory) context.lookup("jms/DURABLE_SUB_CONNECTION_FACTORY"); - assertEquals("testclient", factory2.getClientID()); - } - - @Override - protected String getConnectionFactoryLookupName() { - return "myConnectionFactory"; - } - - @Override - protected void configureEnvironment() { - super.configureEnvironment(); - environment.put("connectionFactoryNames", " myConnectionFactory, jms/Connection, jms/DURABLE_SUB_CONNECTION_FACTORY"); - environment.put("connection.jms/DURABLE_SUB_CONNECTION_FACTORY.clientID", "testclient"); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/DestinationNameWithSlashTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/DestinationNameWithSlashTest.java deleted file mode 100644 index 223fb7da19..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/DestinationNameWithSlashTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.jndi; - -/** - * Test case for AMQ-140 - */ -public class DestinationNameWithSlashTest extends JNDITestSupport { - - public void testNameWithSlash() throws Exception { - assertDestinationExists("jms/Queue"); - - } - - @Override - protected void configureEnvironment() { - super.configureEnvironment(); - environment.put("queue.jms/Queue", "example.myqueue"); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/InitialContextTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/InitialContextTest.java deleted file mode 100644 index adffb4a43b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/InitialContextTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.jndi; - -import javax.naming.Context; -import javax.naming.InitialContext; -import java.util.Properties; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ActiveMQXAConnectionFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class InitialContextTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(InitialContextTest.class); - - public void testInitialContext() throws Exception { - InitialContext context = new InitialContext(); - - ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory) context.lookup("ConnectionFactory"); - - assertTrue("Should have created a ConnectionFactory", connectionFactory != null); - - LOG.info("Created with brokerURL: " + connectionFactory.getBrokerURL()); - - } - - public void testInitialContextHasXA() throws Exception { - InitialContext context = new InitialContext(); - - ActiveMQXAConnectionFactory connectionFactory = (ActiveMQXAConnectionFactory) context.lookup("XAConnectionFactory"); - - assertTrue("Should have created an XAConnectionFactory", connectionFactory != null); - - LOG.info("Created with brokerURL: " + connectionFactory.getBrokerURL()); - - } - - public void testUsingStandardJNDIKeys() throws Exception { - Properties properties = new Properties(); - properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); - String expected = "tcp://localhost:65432"; - properties.put(Context.PROVIDER_URL, expected); - - InitialContext context = new InitialContext(properties); - - ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory) context.lookup("ConnectionFactory"); - - assertTrue("Should have created a ConnectionFactory", connectionFactory != null); - - assertEquals("the brokerURL should match", expected, connectionFactory.getBrokerURL()); - } - - public void testConnectionFactoryPolicyConfig() throws Exception { - - Properties properties = new Properties(); - properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); - properties.put(Context.PROVIDER_URL, "tcp://localhost:65432"); - properties.put("prefetchPolicy.queuePrefetch", "777"); - properties.put("redeliveryPolicy.maximumRedeliveries", "15"); - properties.put("redeliveryPolicy.backOffMultiplier", "32"); - - InitialContext context = new InitialContext(properties); - - ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory) context.lookup("ConnectionFactory"); - - assertTrue("Should have created a ConnectionFactory", connectionFactory != null); - - assertEquals(777, connectionFactory.getPrefetchPolicy().getQueuePrefetch()); - assertEquals(15, connectionFactory.getRedeliveryPolicy().getMaximumRedeliveries()); - assertEquals(32d, connectionFactory.getRedeliveryPolicy().getBackOffMultiplier()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/JNDITestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/JNDITestSupport.java deleted file mode 100644 index bbb5853384..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/JNDITestSupport.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.activemq.jndi; - -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.naming.Binding; -import javax.naming.Context; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.spi.InitialContextFactory; -import java.util.Hashtable; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; - -/** - * - */ -public abstract class JNDITestSupport extends TestCase { - - private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(JNDITestSupport.class); - - protected Hashtable environment = new Hashtable<>(); - protected Context context; - - protected void assertConnectionFactoryPresent(String lookupName) throws NamingException { - Object connectionFactory = context.lookup(lookupName); - - assertTrue("Should have created a ConnectionFactory for key: " + lookupName + " but got: " + connectionFactory, connectionFactory instanceof ConnectionFactory); - } - - protected void assertBinding(Binding binding) throws NamingException { - Object object = binding.getObject(); - assertTrue("Should have got a child context but got: " + object, object instanceof Context); - - Context childContext = (Context) object; - NamingEnumeration iter = childContext.listBindings(""); - while (iter.hasMore()) { - Binding destinationBinding = iter.next(); - LOG.info("Found destination: " + destinationBinding.getName()); - Object destination = destinationBinding.getObject(); - assertTrue("Should have a Destination but got: " + destination, destination instanceof Destination); - } - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - - configureEnvironment(); - - InitialContextFactory factory = new ActiveMQInitialContextFactory(); - context = factory.getInitialContext(environment); - assertTrue("No context created", context != null); - } - - /** - * Stops all existing ActiveMQConnectionFactory in Context. - * - * @throws javax.naming.NamingException - */ - @Override - protected void tearDown() throws NamingException, JMSException { - NamingEnumeration iter = context.listBindings(""); - while (iter.hasMore()) { - Binding binding = iter.next(); - Object connFactory = binding.getObject(); - if (connFactory instanceof ActiveMQConnectionFactory) { - // ((ActiveMQConnectionFactory) connFactory).stop(); - } - } - } - - protected void configureEnvironment() { - environment.put("brokerURL", "vm://localhost"); - } - - protected void assertDestinationExists(String name) throws NamingException { - Object object = context.lookup(name); - assertTrue("Should have received a Destination for name: " + name + " but instead found: " + object, object instanceof Destination); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ObjectFactoryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ObjectFactoryTest.java deleted file mode 100644 index e6855beb0e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/ObjectFactoryTest.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.activemq.jndi; - -import javax.naming.Reference; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.CombinationTestSupport; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; - -public class ObjectFactoryTest extends CombinationTestSupport { - - public void testConnectionFactory() throws Exception { - // Create sample connection factory - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(); - factory.setDispatchAsync(true); - factory.setBrokerURL("vm://test"); - factory.setClientID("test"); - factory.setCopyMessageOnSend(false); - factory.setDisableTimeStampsByDefault(true); - factory.setObjectMessageSerializationDefered(true); - factory.setOptimizedMessageDispatch(false); - factory.setPassword("pass"); - factory.setUseAsyncSend(true); - factory.setUseCompression(true); - factory.setUseRetroactiveConsumer(true); - factory.setUserName("user"); - factory.getPrefetchPolicy().setQueuePrefetch(777); - factory.getRedeliveryPolicy().setMaximumRedeliveries(15); - factory.getRedeliveryPolicy().setBackOffMultiplier((short) 32); - - // Create reference - Reference ref = JNDIReferenceFactory.createReference(factory.getClass().getName(), factory); - - // Get object created based on reference - ActiveMQConnectionFactory temp; - JNDIReferenceFactory refFactory = new JNDIReferenceFactory(); - temp = (ActiveMQConnectionFactory) refFactory.getObjectInstance(ref, null, null, null); - - // Check settings - assertEquals(factory.isDispatchAsync(), temp.isDispatchAsync()); - assertEquals(factory.getBrokerURL(), temp.getBrokerURL()); - assertEquals(factory.getClientID(), temp.getClientID()); - assertEquals(factory.isCopyMessageOnSend(), temp.isCopyMessageOnSend()); - assertEquals(factory.isDisableTimeStampsByDefault(), temp.isDisableTimeStampsByDefault()); - assertEquals(factory.isObjectMessageSerializationDefered(), temp.isObjectMessageSerializationDefered()); - assertEquals(factory.isOptimizedMessageDispatch(), temp.isOptimizedMessageDispatch()); - assertEquals(factory.getPassword(), temp.getPassword()); - assertEquals(factory.isUseAsyncSend(), temp.isUseAsyncSend()); - assertEquals(factory.isUseCompression(), temp.isUseCompression()); - assertEquals(factory.isUseRetroactiveConsumer(), temp.isUseRetroactiveConsumer()); - assertEquals(factory.getUserName(), temp.getUserName()); - assertEquals(factory.getPrefetchPolicy().getQueuePrefetch(), temp.getPrefetchPolicy().getQueuePrefetch()); - assertEquals(factory.getRedeliveryPolicy().getMaximumRedeliveries(), temp.getRedeliveryPolicy().getMaximumRedeliveries()); - assertEquals(factory.getRedeliveryPolicy().getBackOffMultiplier(), temp.getRedeliveryPolicy().getBackOffMultiplier()); - } - - public void testDestination() throws Exception { - // Create sample destination - ActiveMQDestination dest = new ActiveMQQueue(); - dest.setPhysicalName("TEST.FOO"); - - // Create reference - Reference ref = JNDIReferenceFactory.createReference(dest.getClass().getName(), dest); - - // Get object created based on reference - ActiveMQDestination temp; - JNDIReferenceFactory refFactory = new JNDIReferenceFactory(); - temp = (ActiveMQDestination) refFactory.getObjectInstance(ref, null, null, null); - - // Check settings - assertEquals(dest.getPhysicalName(), temp.getPhysicalName()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/XAConnectionFactoryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/XAConnectionFactoryTest.java deleted file mode 100644 index 5b205c0503..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/jndi/XAConnectionFactoryTest.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.activemq.jndi; - -import javax.jms.XAConnectionFactory; -import javax.naming.NamingException; - -public class XAConnectionFactoryTest extends ActiveMQInitialContextFactoryTest { - - public void testConnectionFactoriesIsXA() throws NamingException { - assertTrue("connection factory implements XA", context.lookup(getConnectionFactoryLookupName()) instanceof XAConnectionFactory); - } - - @Override - protected void configureEnvironment() { - environment.put("xa", "true"); - super.configureEnvironment(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/joramtests/ActiveMQAdmin.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/joramtests/ActiveMQAdmin.java deleted file mode 100644 index de226d5cbc..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/joramtests/ActiveMQAdmin.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.activemq.joramtests; - -import javax.jms.ConnectionFactory; -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NamingException; -import java.io.File; -import java.net.URI; -import java.util.Hashtable; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.objectweb.jtests.jms.admin.Admin; - -/** - * @author Hiram Chirino - */ -public class ActiveMQAdmin implements Admin { - - Context context; - - { - try { - // Use the jetty JNDI context since it's mutable. - final Hashtable env = new Hashtable<>(); - env.put("java.naming.factory.initial", "org.eclipse.jetty.jndi.InitialContextFactory"); - env.put("java.naming.factory.url.pkgs", "org.eclipse.jetty.jndi"); - context = new InitialContext(env); - } catch (NamingException e) { - throw new RuntimeException(e); - } - } - - protected BrokerService createBroker() throws Exception { - return BrokerFactory.createBroker(new URI("broker://()/localhost?persistent=false")); - } - - @Override - public String getName() { - return getClass().getName(); - } - - BrokerService broker; - - @Override - public void startServer() throws Exception { - if (System.getProperty("basedir") == null) { - File file = new File("."); - System.setProperty("basedir", file.getAbsolutePath()); - } - broker = createBroker(); - broker.start(); - } - - @Override - public void stopServer() throws Exception { - broker.stop(); - } - - @Override - public void start() throws Exception { - } - - @Override - public void stop() throws Exception { - } - - @Override - public Context createContext() throws NamingException { - return context; - } - - @Override - public void createQueue(String name) { - try { - context.bind(name, new ActiveMQQueue(name)); - } catch (NamingException e) { - throw new RuntimeException(e); - } - } - - @Override - public void createTopic(String name) { - try { - context.bind(name, new ActiveMQTopic(name)); - } catch (NamingException e) { - throw new RuntimeException(e); - } - } - - @Override - public void deleteQueue(String name) { - // BrokerTestSupport.delete_queue((Broker)base.broker, name); - try { - context.unbind(name); - } catch (NamingException e) { - throw new RuntimeException(e); - } - } - - @Override - public void deleteTopic(String name) { - try { - context.unbind(name); - } catch (NamingException e) { - throw new RuntimeException(e); - } - } - - @Override - public void createConnectionFactory(String name) { - try { - final ConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - ((ActiveMQConnectionFactory) factory).setNestedMapAndListEnabled(false); - context.bind(name, factory); - } catch (NamingException e) { - throw new RuntimeException(e); - } - } - - @Override - public void deleteConnectionFactory(String name) { - try { - context.unbind(name); - } catch (NamingException e) { - throw new RuntimeException(e); - } - } - - @Override - public void createQueueConnectionFactory(String name) { - createConnectionFactory(name); - } - - @Override - public void createTopicConnectionFactory(String name) { - createConnectionFactory(name); - } - - @Override - public void deleteQueueConnectionFactory(String name) { - deleteConnectionFactory(name); - } - - @Override - public void deleteTopicConnectionFactory(String name) { - deleteConnectionFactory(name); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/joramtests/JoramJmsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/joramtests/JoramJmsTest.java deleted file mode 100644 index a15f32b89a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/joramtests/JoramJmsTest.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.activemq.joramtests; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -import org.objectweb.jtests.jms.conform.connection.ConnectionTest; -import org.objectweb.jtests.jms.conform.connection.TopicConnectionTest; -import org.objectweb.jtests.jms.conform.message.MessageBodyTest; -import org.objectweb.jtests.jms.conform.message.MessageDefaultTest; -import org.objectweb.jtests.jms.conform.message.MessageTypeTest; -import org.objectweb.jtests.jms.conform.message.headers.MessageHeaderTest; -import org.objectweb.jtests.jms.conform.message.properties.JMSXPropertyTest; -import org.objectweb.jtests.jms.conform.message.properties.MessagePropertyConversionTest; -import org.objectweb.jtests.jms.conform.message.properties.MessagePropertyTest; -import org.objectweb.jtests.jms.conform.queue.QueueBrowserTest; -import org.objectweb.jtests.jms.conform.queue.TemporaryQueueTest; -import org.objectweb.jtests.jms.conform.selector.SelectorSyntaxTest; -import org.objectweb.jtests.jms.conform.selector.SelectorTest; -import org.objectweb.jtests.jms.conform.session.QueueSessionTest; -import org.objectweb.jtests.jms.conform.session.SessionTest; -import org.objectweb.jtests.jms.conform.session.TopicSessionTest; -import org.objectweb.jtests.jms.conform.session.UnifiedSessionTest; -import org.objectweb.jtests.jms.conform.topic.TemporaryTopicTest; - -/** - * @author Hiram Chirino - */ -public class JoramJmsTest extends TestCase { - - public static Test suite() { - TestSuite suite = new TestSuite(); - suite.addTestSuite(SelectorTest.class); - suite.addTestSuite(ConnectionTest.class); - suite.addTestSuite(TopicConnectionTest.class); - suite.addTestSuite(MessageHeaderTest.class); - suite.addTestSuite(MessageBodyTest.class); - suite.addTestSuite(MessageDefaultTest.class); - suite.addTestSuite(MessageTypeTest.class); - suite.addTestSuite(JMSXPropertyTest.class); - suite.addTestSuite(MessagePropertyConversionTest.class); - suite.addTestSuite(TemporaryQueueTest.class); - suite.addTestSuite(SelectorSyntaxTest.class); - suite.addTestSuite(QueueSessionTest.class); - suite.addTestSuite(SessionTest.class); - suite.addTestSuite(TopicSessionTest.class); - suite.addTestSuite(TemporaryTopicTest.class); - suite.addTestSuite(UnifiedSessionTest.class); - suite.addTestSuite(QueueBrowserTest.class); - suite.addTestSuite(MessagePropertyTest.class); - return suite; - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/leveldb/LevelDBStoreBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/leveldb/LevelDBStoreBrokerTest.java deleted file mode 100644 index 6ec80f2623..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/leveldb/LevelDBStoreBrokerTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.leveldb; - -import java.io.File; -import java.io.IOException; - -import junit.framework.Test; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.BrokerTest; -import org.apache.activemq.store.PersistenceAdapter; - -/** - * @author Hiram Chirino - */ -public class LevelDBStoreBrokerTest extends BrokerTest { - - public static Test suite() { - return suite(LevelDBStoreBrokerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setPersistenceAdapter(createPersistenceAdapter(true)); - return broker; - } - - protected PersistenceAdapter createPersistenceAdapter(boolean delete) { - LevelDBStore store = new LevelDBStore(); - store.setDirectory(new File("target/activemq-data/leveldb")); - if (delete) { - store.deleteAllMessages(); - } - return store; - } - - protected BrokerService createRestartedBroker() throws IOException { - BrokerService broker = new BrokerService(); - broker.setPersistenceAdapter(createPersistenceAdapter(false)); - return broker; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/leveldb/LevelDBXARecoveryBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/leveldb/LevelDBXARecoveryBrokerTest.java deleted file mode 100644 index 1c7b7f92fd..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/leveldb/LevelDBXARecoveryBrokerTest.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.activemq.leveldb; - -import java.io.File; -import java.io.IOException; - -import junit.framework.Test; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.XARecoveryBrokerTest; -import org.apache.commons.io.FileUtils; - -/** - * @author Hiram Chirino - */ -public class LevelDBXARecoveryBrokerTest extends XARecoveryBrokerTest { - - public static final String LEVELDB_DIR_BASE = "target/activemq-data/xahaleveldb"; - public static String levelDbDirectoryName; - - @Override - protected void setUp() throws Exception { - levelDbDirectoryName = LEVELDB_DIR_BASE + "/" + System.currentTimeMillis(); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - try { - File levelDbDir = new File(levelDbDirectoryName); - FileUtils.deleteDirectory(levelDbDir); - } catch (IOException e) { - } - } - - public static Test suite() { - return suite(LevelDBXARecoveryBrokerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - @Override - protected void configureBroker(BrokerService broker) throws Exception { - super.configureBroker(broker); - LevelDBStore store = new LevelDBStore(); - store.setDirectory(new File(levelDbDirectoryName)); - broker.setPersistenceAdapter(store); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadClient.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadClient.java deleted file mode 100644 index 556f06da0b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadClient.java +++ /dev/null @@ -1,206 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.load; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; - -import org.apache.activemq.ActiveMQMessageAudit; -import org.apache.activemq.perf.PerfRate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class LoadClient implements Runnable { - - private static final Logger LOG = LoggerFactory.getLogger(LoadClient.class); - protected static int SLEEP_TIME = 2; - protected String name; - protected ConnectionFactory factory; - protected Connection connection; - protected Destination startDestination; - protected Destination nextDestination; - protected Session session; - protected MessageConsumer consumer; - protected MessageProducer producer; - protected PerfRate rate = new PerfRate(); - protected int deliveryMode = DeliveryMode.PERSISTENT; - protected ActiveMQMessageAudit audit = new ActiveMQMessageAudit(); - protected boolean connectionPerMessage = false; - protected boolean running; - protected int timeout = 10000; - - public LoadClient(String name, ConnectionFactory factory) { - this.name = name; - this.factory = factory; - } - - public synchronized void start() throws JMSException { - if (!running) { - rate.reset(); - running = true; - if (!connectionPerMessage) { - connection = factory.createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session.createConsumer(getConsumeDestination()); - producer = session.createProducer(getSendDestination()); - producer.setDeliveryMode(this.deliveryMode); - - } - - Thread t = new Thread(this); - t.setName(name); - t.start(); - } - } - - public void stop() throws JMSException, InterruptedException { - running = false; - if (connection != null) { - connection.stop(); - } - } - - @Override - public void run() { - try { - while (running) { - String result = consume(); - if (result != null) { - send(result); - rate.increment(); - } else if (running) { - LOG.error(name + " Failed to consume!"); - } - } - } catch (Throwable e) { - e.printStackTrace(); - } - } - - protected String consume() throws Exception { - Connection con = null; - MessageConsumer c = consumer; - if (connectionPerMessage) { - con = factory.createConnection(); - con.start(); - Session s = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - c = s.createConsumer(getConsumeDestination()); - } - TextMessage result = (TextMessage) c.receive(timeout); - if (result != null) { - if (audit.isDuplicate(result.getJMSMessageID())) { - throw new JMSException("Received duplicate " + result.getText()); - } - if (!audit.isInOrder(result.getJMSMessageID())) { - throw new JMSException("Out of order " + result.getText()); - } - - if (connectionPerMessage) { - Thread.sleep(SLEEP_TIME);//give the broker a chance - con.close(); - } - } - return result != null ? result.getText() : null; - } - - protected void send(String text) throws Exception { - Connection con = connection; - MessageProducer p = producer; - Session s = session; - if (connectionPerMessage) { - con = factory.createConnection(); - con.start(); - s = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - p = s.createProducer(getSendDestination()); - p.setDeliveryMode(deliveryMode); - } - TextMessage message = s.createTextMessage(text); - p.send(message); - if (connectionPerMessage) { - Thread.sleep(SLEEP_TIME);//give the broker a chance - con.close(); - } - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Destination getStartDestination() { - return startDestination; - } - - public void setStartDestination(Destination startDestination) { - this.startDestination = startDestination; - } - - public Destination getNextDestination() { - return nextDestination; - } - - public void setNextDestination(Destination nextDestination) { - this.nextDestination = nextDestination; - } - - public int getDeliveryMode() { - return deliveryMode; - } - - public void setDeliveryMode(int deliveryMode) { - this.deliveryMode = deliveryMode; - } - - public boolean isConnectionPerMessage() { - return connectionPerMessage; - } - - public void setConnectionPerMessage(boolean connectionPerMessage) { - this.connectionPerMessage = connectionPerMessage; - } - - public int getTimeout() { - return timeout; - } - - public void setTimeout(int timeout) { - this.timeout = timeout; - } - - protected Destination getSendDestination() { - return nextDestination; - } - - protected Destination getConsumeDestination() { - return startDestination; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadController.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadController.java deleted file mode 100644 index 78d93eb9a5..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadController.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.load; - -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.JMSException; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * - */ -public class LoadController extends LoadClient { - - private int numberOfBatches = 1; - private int batchSize = 1000; - private int count; - private final CountDownLatch stopped = new CountDownLatch(1); - - public LoadController(String name, ConnectionFactory factory) { - super(name, factory); - } - - public int awaitTestComplete() throws InterruptedException { - stopped.await(60 * 5, TimeUnit.SECONDS); - return count; - } - - @Override - public void stop() throws JMSException, InterruptedException { - running = false; - stopped.countDown(); - if (connection != null) { - this.connection.stop(); - } - } - - @Override - public void run() { - try { - for (int i = 0; i < numberOfBatches; i++) { - for (int j = 0; j < batchSize; j++) { - String payLoad = "batch[" + i + "]no:" + j; - send(payLoad); - } - for (int j = 0; j < batchSize; j++) { - String result = consume(); - if (result != null) { - count++; - rate.increment(); - } - } - } - } catch (Throwable e) { - e.printStackTrace(); - } finally { - stopped.countDown(); - } - } - - public int getNumberOfBatches() { - return numberOfBatches; - } - - public void setNumberOfBatches(int numberOfBatches) { - this.numberOfBatches = numberOfBatches; - } - - public int getBatchSize() { - return batchSize; - } - - public void setBatchSize(int batchSize) { - this.batchSize = batchSize; - } - - @Override - protected Destination getSendDestination() { - return startDestination; - } - - @Override - protected Destination getConsumeDestination() { - return nextDestination; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadTest.java deleted file mode 100644 index 0eb45d2f6a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadTest.java +++ /dev/null @@ -1,156 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.load; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Session; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class LoadTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(LoadTest.class); - - protected BrokerService broker; - protected String bindAddress = "tcp://localhost:61616"; - - protected LoadController controller; - protected LoadClient[] clients; - protected ConnectionFactory factory; - protected Destination destination; - protected int numberOfClients = 50; - protected int deliveryMode = DeliveryMode.PERSISTENT; - protected int batchSize = 1000; - protected int numberOfBatches = 10; - protected int timeout = Integer.MAX_VALUE; - protected boolean connectionPerMessage = false; - protected Connection managementConnection; - protected Session managementSession; - - /** - * Sets up a test where the producer and consumer have their own connection. - * - * @see junit.framework.TestCase#setUp() - */ - @Override - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(bindAddress); - } - factory = createConnectionFactory(bindAddress); - managementConnection = factory.createConnection(); - managementSession = managementConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - Destination startDestination = createDestination(managementSession, getClass() + ".start"); - Destination endDestination = createDestination(managementSession, getClass() + ".end"); - LOG.info("Running with " + numberOfClients + " clients - sending " + numberOfBatches + " batches of " + batchSize + " messages"); - controller = new LoadController("Controller", factory); - controller.setBatchSize(batchSize); - controller.setNumberOfBatches(numberOfBatches); - controller.setDeliveryMode(deliveryMode); - controller.setConnectionPerMessage(connectionPerMessage); - controller.setStartDestination(startDestination); - controller.setNextDestination(endDestination); - controller.setTimeout(timeout); - clients = new LoadClient[numberOfClients]; - for (int i = 0; i < numberOfClients; i++) { - Destination inDestination = null; - if (i == 0) { - inDestination = startDestination; - } else { - inDestination = createDestination(managementSession, getClass() + ".client." + (i)); - } - Destination outDestination = null; - if (i == (numberOfClients - 1)) { - outDestination = endDestination; - } else { - outDestination = createDestination(managementSession, getClass() + ".client." + (i + 1)); - } - LoadClient client = new LoadClient("client(" + i + ")", factory); - client.setTimeout(timeout); - client.setDeliveryMode(deliveryMode); - client.setConnectionPerMessage(connectionPerMessage); - client.setStartDestination(inDestination); - client.setNextDestination(outDestination); - clients[i] = client; - } - - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - managementConnection.close(); - for (int i = 0; i < numberOfClients; i++) { - clients[i].stop(); - } - controller.stop(); - if (broker != null) { - broker.stop(); - broker = null; - } - } - - protected Destination createDestination(Session s, String destinationName) throws JMSException { - return s.createQueue(destinationName); - } - - /** - * Factory method to create a new broker - * - * @throws Exception - */ - protected BrokerService createBroker(String uri) throws Exception { - BrokerService answer = new BrokerService(); - configureBroker(answer, uri); - answer.start(); - return answer; - } - - protected void configureBroker(BrokerService answer, String uri) throws Exception { - answer.setDeleteAllMessagesOnStartup(true); - answer.addConnector(uri); - answer.setUseShutdownHook(false); - } - - protected ActiveMQConnectionFactory createConnectionFactory(String uri) throws Exception { - return new ActiveMQConnectionFactory(uri); - } - - public void testLoad() throws JMSException, InterruptedException { - for (int i = 0; i < numberOfClients; i++) { - clients[i].start(); - } - controller.start(); - assertEquals((batchSize * numberOfBatches), controller.awaitTestComplete()); - - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/BoundaryStatisticTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/BoundaryStatisticTest.java deleted file mode 100644 index f53a06e8f4..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/BoundaryStatisticTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.management; - -public class BoundaryStatisticTest extends StatisticTestSupport { - - private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(BoundaryStatisticTest.class); - - /** - * Use case for BoundaryStatisticImpl class. - * - * @throws Exception - */ - public void testStatistic() throws Exception { - BoundaryStatisticImpl stat = new BoundaryStatisticImpl("myBoundaryStat", "seconds", "myBoundaryStatDesc", 1000, 2000); - assertStatistic(stat, "myBoundaryStat", "seconds", "myBoundaryStatDesc"); - - assertEquals(1000, stat.getLowerBound()); - assertEquals(2000, stat.getUpperBound()); - - LOG.info("Stat is: " + stat); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/BoundedRangeStatisticTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/BoundedRangeStatisticTest.java deleted file mode 100644 index 1c5d497a95..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/BoundedRangeStatisticTest.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.activemq.management; - -/** - * - */ -public class BoundedRangeStatisticTest extends RangeStatisticTest { - - /** - * Use case for BoundedRangeStatisticImpl class. - * - * @throws Exception - */ - @Override - public void testStatistic() throws Exception { - BoundedRangeStatisticImpl stat = new BoundedRangeStatisticImpl("myRange", "millis", "myDescription", 10, 3000); - assertStatistic(stat, "myRange", "millis", "myDescription"); - assertEquals(10, stat.getLowerBound()); - assertEquals(3000, stat.getUpperBound()); - - assertRangeStatistic(stat); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/CountStatisticTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/CountStatisticTest.java deleted file mode 100644 index fff320df32..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/CountStatisticTest.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.activemq.management; - -public class CountStatisticTest extends StatisticTestSupport { - - private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(CountStatisticTest.class); - - /** - * Use case for CountStatisticImple class. - * - * @throws Exception - */ - public void testStatistic() throws Exception { - CountStatisticImpl stat = new CountStatisticImpl("myCounter", "seconds", "myDescription"); - stat.setEnabled(true); - assertStatistic(stat, "myCounter", "seconds", "myDescription"); - - assertEquals(0, stat.getCount()); - - stat.increment(); - assertEquals(1, stat.getCount()); - - stat.increment(); - assertEquals(2, stat.getCount()); - - stat.decrement(); - assertEquals(1, stat.getCount()); - - Thread.sleep(500); - - stat.increment(); - - assertLastTimeNotStartTime(stat); - - LOG.info("Counter is: " + stat); - - stat.reset(); - - assertEquals(0, stat.getCount()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/RangeStatisticTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/RangeStatisticTest.java deleted file mode 100644 index a44dc6108b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/RangeStatisticTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.management; - -public class RangeStatisticTest extends StatisticTestSupport { - - private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(RangeStatisticTest.class); - - /** - * Use case for RangeStatisticImpl class. - * - * @throws Exception - */ - public void testStatistic() throws Exception { - RangeStatisticImpl stat = new RangeStatisticImpl("myRange", "millis", "myDescription"); - assertStatistic(stat, "myRange", "millis", "myDescription"); - - assertRangeStatistic(stat); - } - - protected void assertRangeStatistic(RangeStatisticImpl stat) throws InterruptedException { - assertEquals(0, stat.getCurrent()); - assertEquals(0, stat.getLowWaterMark()); - assertEquals(0, stat.getHighWaterMark()); - - stat.setCurrent(100); - assertEquals(100, stat.getCurrent()); - assertEquals(100, stat.getLowWaterMark()); - assertEquals(100, stat.getHighWaterMark()); - - stat.setCurrent(50); - assertEquals(50, stat.getCurrent()); - assertEquals(50, stat.getLowWaterMark()); - assertEquals(100, stat.getHighWaterMark()); - - stat.setCurrent(200); - assertEquals(200, stat.getCurrent()); - assertEquals(50, stat.getLowWaterMark()); - assertEquals(200, stat.getHighWaterMark()); - - Thread.sleep(500); - - stat.setCurrent(10); - assertEquals(10, stat.getCurrent()); - assertEquals(10, stat.getLowWaterMark()); - assertEquals(200, stat.getHighWaterMark()); - - assertLastTimeNotStartTime(stat); - - LOG.info("Stat is: " + stat); - - stat.reset(); - - assertEquals(0, stat.getCurrent()); - assertEquals(0, stat.getLowWaterMark()); - assertEquals(0, stat.getHighWaterMark()); - - stat.setCurrent(100); - assertEquals(100, stat.getCurrent()); - assertEquals(100, stat.getLowWaterMark()); - assertEquals(100, stat.getHighWaterMark()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/StatisticTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/StatisticTestSupport.java deleted file mode 100644 index c96287ef20..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/StatisticTestSupport.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.management; - -import junit.framework.TestCase; - -public abstract class StatisticTestSupport extends TestCase { - - /** - * assert method used by the management related classes for its usecase. - * - * @param counter - * @param name - * @param unit - * @param description - */ - protected void assertStatistic(StatisticImpl counter, String name, String unit, String description) { - assertEquals(name, counter.getName()); - assertEquals(unit, counter.getUnit()); - assertEquals(description, counter.getDescription()); - } - - /** - * assert method to determine last time vs the start time. - * - * @param counter - */ - protected void assertLastTimeNotStartTime(StatisticImpl counter) { - assertTrue("Should not have start time the same as last sample time. Start time: " + counter.getStartTime() + " lastTime: " + counter.getLastSampleTime(), counter.getStartTime() != counter.getLastSampleTime()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/TimeStatisticTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/TimeStatisticTest.java deleted file mode 100644 index de20b19fde..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/management/TimeStatisticTest.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.activemq.management; - -public class TimeStatisticTest extends StatisticTestSupport { - - private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(TimeStatisticTest.class); - - /** - * Use case for TimeStatisticImpl class. - * - * @throws Exception - */ - public void testStatistic() throws Exception { - TimeStatisticImpl stat = new TimeStatisticImpl("myTimer", "millis", "myDescription"); - assertStatistic(stat, "myTimer", "millis", "myDescription"); - - assertEquals(0, stat.getCount()); - - stat.addTime(100); - assertEquals(1, stat.getCount()); - assertEquals(100, stat.getMinTime()); - assertEquals(100, stat.getMaxTime()); - - stat.addTime(403); - assertEquals(2, stat.getCount()); - assertEquals(100, stat.getMinTime()); - assertEquals(403, stat.getMaxTime()); - - stat.addTime(50); - assertEquals(3, stat.getCount()); - assertEquals(50, stat.getMinTime()); - assertEquals(403, stat.getMaxTime()); - - assertEquals(553, stat.getTotalTime()); - - Thread.sleep(500); - - stat.addTime(10); - - assertLastTimeNotStartTime(stat); - - LOG.info("Stat is: " + stat); - - stat.reset(); - - assertEquals(0, stat.getCount()); - assertEquals(0, stat.getMinTime()); - assertEquals(0, stat.getMaxTime()); - assertEquals(0, stat.getTotalTime()); - - stat.addTime(100); - assertEquals(1, stat.getCount()); - assertEquals(100, stat.getMinTime()); - assertEquals(100, stat.getMaxTime()); - assertEquals(100, stat.getTotalTime()); - - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/MemoryPropertyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/MemoryPropertyTest.java deleted file mode 100644 index f4d904f9b5..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/MemoryPropertyTest.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.activemq.memory; - -import junit.framework.TestCase; - -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MemoryPropertyTest extends TestCase { - - private static final transient Logger LOG = LoggerFactory.getLogger(MemoryPropertyTest.class); - BrokerService broker; - - /** - * Sets up a test where the producer and consumer have their own connection. - * - * @see junit.framework.TestCase#setUp() - */ - @Override - protected void setUp() throws Exception { - // Create broker from resource - LOG.info("Creating broker... "); - broker = createBroker("xbean:org/apache/activemq/memory/activemq.xml"); - LOG.info("Success"); - super.setUp(); - } - - protected BrokerService createBroker(String resource) throws Exception { - return BrokerFactory.createBroker(resource); - } - - /* - * Stops the Broker - * - * @see junit.framework.TestCase#tearDown() - */ - @Override - protected void tearDown() throws Exception { - LOG.info("Closing Broker"); - if (broker != null) { - broker.stop(); - } - LOG.info("Broker closed..."); - } - - public void testBrokerInitialized() { - assertTrue("We should have a broker", broker != null); - - assertEquals("test-broker", broker.getBrokerName()); - assertEquals(1024, broker.getSystemUsage().getMemoryUsage().getLimit()); - assertEquals(34, broker.getSystemUsage().getMemoryUsage().getPercentUsageMinDelta()); - - assertNotNull(broker.getSystemUsage().getStoreUsage().getStore()); - // non persistent broker so no temp storage - assertNull(broker.getSystemUsage().getTempUsage().getStore()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/activemq.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/activemq.xml deleted file mode 100644 index 511d6d1925..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/activemq.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/DummyMessage.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/DummyMessage.java deleted file mode 100644 index 74946b3f16..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/DummyMessage.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.activemq.memory.buffer; - -import org.apache.activemq.command.ActiveMQMessage; - -/** - * A message implementation which is useful for testing as we can spoof its size - */ -public class DummyMessage extends ActiveMQMessage { - - private int size; - - public DummyMessage(int size) { - this.size = size; - } - - @Override - public int getSize() { - return size; - } - - @Override - public String toString() { - return "DummyMessage[id=" + getMessageId() + " size=" + size + "]"; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/MemoryBufferTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/MemoryBufferTestSupport.java deleted file mode 100644 index f7e0260e5d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/MemoryBufferTestSupport.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.memory.buffer; - -import junit.framework.TestCase; - -import org.apache.activemq.command.ActiveMQMessage; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * - */ -public abstract class MemoryBufferTestSupport extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(MemoryBufferTestSupport.class); - - protected MessageBuffer buffer = createMessageBuffer(); - protected MessageQueue qA = buffer.createMessageQueue(); - protected MessageQueue qB = buffer.createMessageQueue(); - protected MessageQueue qC = buffer.createMessageQueue(); - protected int messageCount; - - protected abstract MessageBuffer createMessageBuffer(); - - @Override - protected void setUp() throws Exception { - buffer = createMessageBuffer(); - qA = buffer.createMessageQueue(); - qB = buffer.createMessageQueue(); - qC = buffer.createMessageQueue(); - } - - protected void dump() { - LOG.info("Dumping current state"); - dumpQueue(qA, "A"); - dumpQueue(qB, "B"); - dumpQueue(qC, "C"); - } - - protected void dumpQueue(MessageQueue queue, String name) { - LOG.info(" " + name + " = " + queue.getList()); - } - - protected ActiveMQMessage createMessage(int size) throws Exception { - DummyMessage answer = new DummyMessage(size); - answer.setIntProperty("counter", ++messageCount); - answer.setJMSMessageID("" + messageCount); - return answer; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/OrderBasedMemoryBufferTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/OrderBasedMemoryBufferTest.java deleted file mode 100644 index 8ddf594499..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/OrderBasedMemoryBufferTest.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.activemq.memory.buffer; - -/** - * - * - */ -public class OrderBasedMemoryBufferTest extends MemoryBufferTestSupport { - - public void testSizeWorks() throws Exception { - qA.add(createMessage(10)); - qB.add(createMessage(10)); - qB.add(createMessage(10)); - qC.add(createMessage(10)); - - dump(); - - assertEquals("buffer size", 40, buffer.getSize()); - assertEquals("qA", 10, qA.getSize()); - assertEquals("qB", 20, qB.getSize()); - assertEquals("qC", 10, qC.getSize()); - - qC.add(createMessage(10)); - - dump(); - - assertEquals("buffer size", 40, buffer.getSize()); - assertEquals("qA", 0, qA.getSize()); - assertEquals("qB", 20, qB.getSize()); - assertEquals("qC", 20, qC.getSize()); - - qB.add(createMessage(10)); - - dump(); - - assertEquals("buffer size", 40, buffer.getSize()); - assertEquals("qA", 0, qA.getSize()); - assertEquals("qB", 20, qB.getSize()); - assertEquals("qC", 20, qC.getSize()); - - qA.add(createMessage(10)); - - dump(); - - assertEquals("buffer size", 40, buffer.getSize()); - assertEquals("qA", 10, qA.getSize()); - assertEquals("qB", 10, qB.getSize()); - assertEquals("qC", 20, qC.getSize()); - } - - @Override - protected MessageBuffer createMessageBuffer() { - return new OrderBasedMessageBuffer(40); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/SizeBasedMessageBufferTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/SizeBasedMessageBufferTest.java deleted file mode 100644 index 2329c5f0ae..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/buffer/SizeBasedMessageBufferTest.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.activemq.memory.buffer; - -/** - * - * - */ -public class SizeBasedMessageBufferTest extends MemoryBufferTestSupport { - - public void testSizeWorks() throws Exception { - qA.add(createMessage(10)); - qB.add(createMessage(10)); - qB.add(createMessage(10)); - qC.add(createMessage(10)); - - dump(); - - assertEquals("buffer size", 40, buffer.getSize()); - assertEquals("qA", 10, qA.getSize()); - assertEquals("qB", 20, qB.getSize()); - assertEquals("qC", 10, qC.getSize()); - - // now lets force an eviction - qC.add(createMessage(10)); - - dump(); - - assertEquals("buffer size", 40, buffer.getSize()); - assertEquals("qA", 10, qA.getSize()); - assertEquals("qB", 10, qB.getSize()); - assertEquals("qC", 20, qC.getSize()); - } - - @Override - protected MessageBuffer createMessageBuffer() { - return new SizeBasedMessageBuffer(40); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/usage.properties b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/usage.properties deleted file mode 100644 index b5d33d12a9..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/memory/usage.properties +++ /dev/null @@ -1,19 +0,0 @@ -## --------------------------------------------------------------------------- -## Licensed to the Apache Software Foundation (ASF) under one or more -## contributor license agreements. See the NOTICE file distributed with -## this work for additional information regarding copyright ownership. -## The ASF licenses this file to You under the Apache License, Version 2.0 -## (the "License"); you may not use this file except in compliance with -## the License. You may obtain a copy of the License at -## -## http://www.apache.org/licenses/LICENSE-2.0 -## -## Unless required by applicable law or agreed to in writing, software -## distributed under the License is distributed on an "AS IS" BASIS, -## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -## See the License for the specific language governing permissions and -## limitations under the License. -## --------------------------------------------------------------------------- -limit=1k -name=test-broker -delta=34 \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/BrokerNetworkWithStuckMessagesTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/BrokerNetworkWithStuckMessagesTest.java deleted file mode 100644 index ce7c5eae9d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/BrokerNetworkWithStuckMessagesTest.java +++ /dev/null @@ -1,626 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.MessageNotWriteableException; -import javax.jms.Queue; -import javax.jms.QueueBrowser; -import javax.jms.Session; -import javax.management.ObjectName; -import javax.management.openmbean.CompositeData; -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.BrokerTestSupport; -import org.apache.activemq.broker.StubConnection; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.broker.jmx.ManagementContext; -import org.apache.activemq.broker.jmx.QueueViewMBean; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQMessage; -import org.apache.activemq.command.ActiveMQTextMessage; -import org.apache.activemq.command.ConnectionId; -import org.apache.activemq.command.ConnectionInfo; -import org.apache.activemq.command.ConsumerInfo; -import org.apache.activemq.command.DestinationInfo; -import org.apache.activemq.command.Message; -import org.apache.activemq.command.MessageAck; -import org.apache.activemq.command.MessageDispatch; -import org.apache.activemq.command.MessageId; -import org.apache.activemq.command.ProducerInfo; -import org.apache.activemq.command.SessionInfo; -import org.apache.activemq.transport.Transport; -import org.apache.activemq.transport.TransportFactory; -import org.apache.activemq.util.Wait; -import org.apache.commons.io.FileUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -/** - * This class duplicates most of the functionality in {@link NetworkTestSupport} - * and {@link BrokerTestSupport} because more control was needed over how brokers - * and connectors are created. Also, this test asserts message counts via JMX on - * each broker. - */ -public class BrokerNetworkWithStuckMessagesTest { - - private static final Logger LOG = LoggerFactory.getLogger(BrokerNetworkWithStuckMessagesTest.class); - - private BrokerService localBroker; - private BrokerService remoteBroker; - private BrokerService secondRemoteBroker; - private DemandForwardingBridge bridge; - - protected Map brokers = new HashMap<>(); - protected ArrayList connections = new ArrayList<>(); - - protected TransportConnector connector; - protected TransportConnector remoteConnector; - protected TransportConnector secondRemoteConnector; - - protected long idGenerator; - protected int msgIdGenerator; - protected int tempDestGenerator; - protected int maxWait = 4000; - protected String queueName = "TEST"; - - protected String amqDomain = "org.apache.activemq"; - - @Before - public void setUp() throws Exception { - - // For those who want visual confirmation: - // Uncomment the following to enable JMX support on a port number to use - // Jconsole to view each broker. You will need to add some calls to - // Thread.sleep() to be able to actually slow things down so that you - // can manually see JMX attrs. - // System.setProperty("com.sun.management.jmxremote", ""); - // System.setProperty("com.sun.management.jmxremote.port", "1099"); - // System.setProperty("com.sun.management.jmxremote.authenticate", "false"); - // System.setProperty("com.sun.management.jmxremote.ssl", "false"); - - // Create the local broker - createBroker(); - // Create the remote broker - createRemoteBroker(); - - // Remove the activemq-data directory from the creation of the remote broker - FileUtils.deleteDirectory(new File("activemq-data")); - - // Create a network bridge between the local and remote brokers so that - // demand-based forwarding can take place - NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); - config.setBrokerName("local"); - config.setDispatchAsync(false); - config.setDuplex(true); - - Transport localTransport = createTransport(); - Transport remoteTransport = createRemoteTransport(); - - // Create a network bridge between the two brokers - bridge = new DemandForwardingBridge(config, localTransport, remoteTransport); - bridge.setBrokerService(localBroker); - bridge.start(); - - // introduce a second broker/bridge on remote that should not get any messages because of networkTtl=1 - // local <-> remote <-> secondRemote - createSecondRemoteBroker(); - config = new NetworkBridgeConfiguration(); - config.setBrokerName("remote"); - config.setDuplex(true); - - localTransport = createRemoteTransport(); - remoteTransport = createSecondRemoteTransport(); - - // Create a network bridge between the two brokers - bridge = new DemandForwardingBridge(config, localTransport, remoteTransport); - bridge.setBrokerService(remoteBroker); - bridge.start(); - - waitForBridgeFormation(); - } - - protected void waitForBridgeFormation() throws Exception { - for (final BrokerService broker : brokers.values()) { - if (!broker.getNetworkConnectors().isEmpty()) { - // Max wait here is 30 secs - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return !broker.getNetworkConnectors().get(0).activeBridges().isEmpty(); - } - }); - } - } - } - - @After - public void tearDown() throws Exception { - bridge.stop(); - localBroker.stop(); - remoteBroker.stop(); - secondRemoteBroker.stop(); - } - - @Test(timeout = 120000) - public void testBrokerNetworkWithStuckMessages() throws Exception { - - int sendNumMessages = 10; - int receiveNumMessages = 5; - - // Create a producer - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo); - - // Create a destination on the local broker - ActiveMQDestination destinationInfo1 = null; - - // Send a 10 messages to the local broker - for (int i = 0; i < sendNumMessages; ++i) { - destinationInfo1 = createDestinationInfo(connection1, connectionInfo1, ActiveMQDestination.QUEUE_TYPE); - connection1.request(createMessage(producerInfo, destinationInfo1, DeliveryMode.NON_PERSISTENT)); - } - - // Ensure that there are 10 messages on the local broker - Object[] messages = browseQueueWithJmx(localBroker); - assertEquals(sendNumMessages, messages.length); - - // Create a synchronous consumer on the remote broker - StubConnection connection2 = createRemoteConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - ActiveMQDestination destinationInfo2 = createDestinationInfo(connection2, connectionInfo2, ActiveMQDestination.QUEUE_TYPE); - final ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destinationInfo2); - connection2.send(consumerInfo2); - - // Consume 5 of the messages from the remote broker and ack them. - for (int i = 0; i < receiveNumMessages; ++i) { - Message message1 = receiveMessage(connection2, 20000); - assertNotNull(message1); - LOG.info("on remote, got: " + message1.getMessageId()); - connection2.send(createAck(consumerInfo2, message1, 1, MessageAck.INDIVIDUAL_ACK_TYPE)); - assertTrue("JMSActiveMQBrokerPath property present and correct", ((ActiveMQMessage) message1).getStringProperty(ActiveMQMessage.BROKER_PATH_PROPERTY).contains(localBroker.getBroker().getBrokerId().toString())); - } - - // Ensure that there are zero messages on the local broker. This tells - // us that those messages have been prefetched to the remote broker - // where the demand exists. - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Object[] result = browseQueueWithJmx(localBroker); - return 0 == result.length; - } - }); - messages = browseQueueWithJmx(localBroker); - assertEquals(0, messages.length); - - // try and pull the messages from remote, should be denied b/c on networkTtl - LOG.info("creating demand on second remote..."); - StubConnection connection3 = createSecondRemoteConnection(); - ConnectionInfo connectionInfo3 = createConnectionInfo(); - SessionInfo sessionInfo3 = createSessionInfo(connectionInfo3); - connection3.send(connectionInfo3); - connection3.send(sessionInfo3); - ActiveMQDestination destinationInfo3 = createDestinationInfo(connection3, connectionInfo3, ActiveMQDestination.QUEUE_TYPE); - final ConsumerInfo consumerInfoS3 = createConsumerInfo(sessionInfo3, destinationInfo3); - connection3.send(consumerInfoS3); - - Message messageExceedingTtl = receiveMessage(connection3, 5000); - if (messageExceedingTtl != null) { - LOG.error("got message on Second remote: " + messageExceedingTtl); - connection3.send(createAck(consumerInfoS3, messageExceedingTtl, 1, MessageAck.INDIVIDUAL_ACK_TYPE)); - } - - LOG.info("Closing consumer on remote"); - // Close the consumer on the remote broker - connection2.send(consumerInfo2.createRemoveCommand()); - // also close connection etc.. so messages get dropped from the local consumer q - connection2.send(connectionInfo2.createRemoveCommand()); - - // There should now be 5 messages stuck on the remote broker - assertTrue("correct stuck message count", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Object[] result = browseQueueWithJmx(remoteBroker); - return 5 == result.length; - } - })); - messages = browseQueueWithJmx(remoteBroker); - assertEquals(5, messages.length); - - assertTrue("can see broker path property", ((String) ((CompositeData) messages[1]).get("BrokerPath")).contains(localBroker.getBroker().getBrokerId().toString())); - - LOG.info("Messages now stuck on remote"); - - // receive again on the origin broker - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destinationInfo1); - connection1.send(consumerInfo1); - LOG.info("create local consumer: " + consumerInfo1); - - Message message1 = receiveMessage(connection1, 20000); - assertNotNull("Expect to get a replay as remote consumer is gone", message1); - connection1.send(createAck(consumerInfo1, message1, 1, MessageAck.INDIVIDUAL_ACK_TYPE)); - LOG.info("acked one message on origin, waiting for all messages to percolate back"); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Object[] result = browseQueueWithJmx(localBroker); - return 4 == result.length; - } - }); - messages = browseQueueWithJmx(localBroker); - assertEquals(4, messages.length); - - LOG.info("checking for messages on remote again"); - // messages won't migrate back again till consumer closes - connection2 = createRemoteConnection(); - connectionInfo2 = createConnectionInfo(); - sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - ConsumerInfo consumerInfo3 = createConsumerInfo(sessionInfo2, destinationInfo2); - connection2.send(consumerInfo3); - message1 = receiveMessage(connection2, 20000); - assertNull("Messages have migrated back: " + message1, message1); - - // Consume the last 4 messages from the local broker and ack them just - // to clean up the queue. - int counter = 1; - for (; counter < receiveNumMessages; counter++) { - message1 = receiveMessage(connection1); - LOG.info("local consume of: " + (message1 != null ? message1.getMessageId() : " null")); - connection1.send(createAck(consumerInfo1, message1, 1, MessageAck.INDIVIDUAL_ACK_TYPE)); - } - // Ensure that 5 messages were received - assertEquals(receiveNumMessages, counter); - - // verify all messages consumed - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Object[] result = browseQueueWithJmx(remoteBroker); - return 0 == result.length; - } - }); - messages = browseQueueWithJmx(remoteBroker); - assertEquals(0, messages.length); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Object[] result = browseQueueWithJmx(localBroker); - return 0 == result.length; - } - }); - messages = browseQueueWithJmx(localBroker); - assertEquals(0, messages.length); - - // Close the consumer on the remote broker - connection2.send(consumerInfo3.createRemoveCommand()); - - connection1.stop(); - connection2.stop(); - connection3.stop(); - } - - protected BrokerService createBroker() throws Exception { - localBroker = new BrokerService(); - localBroker.setBrokerName("localhost"); - localBroker.setUseJmx(true); - localBroker.setPersistenceAdapter(null); - localBroker.setPersistent(false); - connector = createConnector(); - localBroker.addConnector(connector); - configureBroker(localBroker); - localBroker.start(); - localBroker.waitUntilStarted(); - - localBroker.getManagementContext().setConnectorPort(2221); - - brokers.put(localBroker.getBrokerName(), localBroker); - - return localBroker; - } - - private void configureBroker(BrokerService broker) { - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setExpireMessagesPeriod(0); - ConditionalNetworkBridgeFilterFactory filterFactory = new ConditionalNetworkBridgeFilterFactory(); - filterFactory.setReplayWhenNoConsumers(true); - defaultEntry.setNetworkBridgeFilterFactory(filterFactory); - policyMap.setDefaultEntry(defaultEntry); - broker.setDestinationPolicy(policyMap); - } - - protected BrokerService createRemoteBroker() throws Exception { - remoteBroker = new BrokerService(); - remoteBroker.setBrokerName("remotehost"); - remoteBroker.setUseJmx(true); - remoteBroker.setPersistenceAdapter(null); - remoteBroker.setPersistent(false); - remoteConnector = createRemoteConnector(); - remoteBroker.addConnector(remoteConnector); - configureBroker(remoteBroker); - remoteBroker.start(); - remoteBroker.waitUntilStarted(); - - remoteBroker.getManagementContext().setConnectorPort(2222); - - brokers.put(remoteBroker.getBrokerName(), remoteBroker); - - return remoteBroker; - } - - protected BrokerService createSecondRemoteBroker() throws Exception { - secondRemoteBroker = new BrokerService(); - secondRemoteBroker.setBrokerName("secondRemotehost"); - secondRemoteBroker.setUseJmx(false); - secondRemoteBroker.setPersistenceAdapter(null); - secondRemoteBroker.setPersistent(false); - secondRemoteConnector = createSecondRemoteConnector(); - secondRemoteBroker.addConnector(secondRemoteConnector); - configureBroker(secondRemoteBroker); - secondRemoteBroker.start(); - secondRemoteBroker.waitUntilStarted(); - - brokers.put(secondRemoteBroker.getBrokerName(), secondRemoteBroker); - - return secondRemoteBroker; - } - - protected Transport createTransport() throws Exception { - Transport transport = TransportFactory.connect(connector.getServer().getConnectURI()); - return transport; - } - - protected Transport createRemoteTransport() throws Exception { - Transport transport = TransportFactory.connect(remoteConnector.getServer().getConnectURI()); - return transport; - } - - protected Transport createSecondRemoteTransport() throws Exception { - Transport transport = TransportFactory.connect(secondRemoteConnector.getServer().getConnectURI()); - return transport; - } - - protected TransportConnector createConnector() throws Exception, IOException, URISyntaxException { - return new TransportConnector(TransportFactory.bind(new URI(getLocalURI()))); - } - - protected TransportConnector createRemoteConnector() throws Exception, IOException, URISyntaxException { - return new TransportConnector(TransportFactory.bind(new URI(getRemoteURI()))); - } - - protected TransportConnector createSecondRemoteConnector() throws Exception, IOException, URISyntaxException { - return new TransportConnector(TransportFactory.bind(new URI(getSecondRemoteURI()))); - } - - protected String getRemoteURI() { - return "vm://remotehost"; - } - - protected String getSecondRemoteURI() { - return "vm://secondRemotehost"; - } - - protected String getLocalURI() { - return "vm://localhost"; - } - - protected StubConnection createConnection() throws Exception { - Transport transport = TransportFactory.connect(connector.getServer().getConnectURI()); - StubConnection connection = new StubConnection(transport); - connections.add(connection); - return connection; - } - - protected StubConnection createRemoteConnection() throws Exception { - Transport transport = TransportFactory.connect(remoteConnector.getServer().getConnectURI()); - StubConnection connection = new StubConnection(transport); - connections.add(connection); - return connection; - } - - protected StubConnection createSecondRemoteConnection() throws Exception { - Transport transport = TransportFactory.connect(secondRemoteConnector.getServer().getConnectURI()); - StubConnection connection = new StubConnection(transport); - connections.add(connection); - return connection; - } - - @SuppressWarnings("unused") - private Object[] browseQueueWithJms(BrokerService broker) throws Exception { - Object[] messages = null; - Connection connection = null; - Session session = null; - - try { - URI brokerUri = connector.getUri(); - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUri.toString()); - connection = connectionFactory.createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue destination = session.createQueue(queueName); - QueueBrowser browser = session.createBrowser(destination); - List list = new ArrayList<>(); - for (Enumeration enumn = browser.getEnumeration(); enumn.hasMoreElements(); ) { - list.add(enumn.nextElement()); - } - messages = list.toArray(); - } finally { - if (session != null) { - session.close(); - } - if (connection != null) { - connection.close(); - } - } - LOG.info("+Browsed with JMS: " + messages.length); - - return messages; - } - - private Object[] browseQueueWithJmx(BrokerService broker) throws Exception { - Hashtable params = new Hashtable<>(); - params.put("brokerName", broker.getBrokerName()); - params.put("type", "Broker"); - params.put("destinationType", "Queue"); - params.put("destinationName", queueName); - ObjectName queueObjectName = ObjectName.getInstance(amqDomain, params); - - ManagementContext mgmtCtx = broker.getManagementContext(); - QueueViewMBean queueView = (QueueViewMBean) mgmtCtx.newProxyInstance(queueObjectName, QueueViewMBean.class, true); - - Object[] messages = queueView.browse(); - - LOG.info("+Browsed with JMX: " + messages.length); - - return messages; - } - - protected ConnectionInfo createConnectionInfo() throws Exception { - ConnectionInfo info = new ConnectionInfo(); - info.setConnectionId(new ConnectionId("connection:" + (++idGenerator))); - info.setClientId(info.getConnectionId().getValue()); - return info; - } - - protected SessionInfo createSessionInfo(ConnectionInfo connectionInfo) throws Exception { - SessionInfo info = new SessionInfo(connectionInfo, ++idGenerator); - return info; - } - - protected ProducerInfo createProducerInfo(SessionInfo sessionInfo) throws Exception { - ProducerInfo info = new ProducerInfo(sessionInfo, ++idGenerator); - return info; - } - - protected ConsumerInfo createConsumerInfo(SessionInfo sessionInfo, - ActiveMQDestination destination) throws Exception { - ConsumerInfo info = new ConsumerInfo(sessionInfo, ++idGenerator); - info.setBrowser(false); - info.setDestination(destination); - info.setPrefetchSize(1000); - info.setDispatchAsync(false); - return info; - } - - protected DestinationInfo createTempDestinationInfo(ConnectionInfo connectionInfo, byte destinationType) { - DestinationInfo info = new DestinationInfo(); - info.setConnectionId(connectionInfo.getConnectionId()); - info.setOperationType(DestinationInfo.ADD_OPERATION_TYPE); - info.setDestination(ActiveMQDestination.createDestination(info.getConnectionId() + ":" + (++tempDestGenerator), destinationType)); - return info; - } - - protected ActiveMQDestination createDestinationInfo(StubConnection connection, - ConnectionInfo connectionInfo1, - byte destinationType) throws Exception { - if ((destinationType & ActiveMQDestination.TEMP_MASK) != 0) { - DestinationInfo info = createTempDestinationInfo(connectionInfo1, destinationType); - connection.send(info); - return info.getDestination(); - } else { - return ActiveMQDestination.createDestination(queueName, destinationType); - } - } - - protected Message createMessage(ProducerInfo producerInfo, ActiveMQDestination destination, int deliveryMode) { - Message message = createMessage(producerInfo, destination); - message.setPersistent(deliveryMode == DeliveryMode.PERSISTENT); - return message; - } - - protected Message createMessage(ProducerInfo producerInfo, ActiveMQDestination destination) { - ActiveMQTextMessage message = new ActiveMQTextMessage(); - message.setMessageId(new MessageId(producerInfo, ++msgIdGenerator)); - message.setDestination(destination); - message.setPersistent(false); - try { - message.setText("Test Message Payload."); - } catch (MessageNotWriteableException e) { - } - return message; - } - - protected MessageAck createAck(ConsumerInfo consumerInfo, Message msg, int count, byte ackType) { - MessageAck ack = new MessageAck(); - ack.setAckType(ackType); - ack.setConsumerId(consumerInfo.getConsumerId()); - ack.setDestination(msg.getDestination()); - ack.setLastMessageId(msg.getMessageId()); - ack.setMessageCount(count); - return ack; - } - - public Message receiveMessage(StubConnection connection) throws InterruptedException { - return receiveMessage(connection, maxWait); - } - - public Message receiveMessage(StubConnection connection, long timeout) throws InterruptedException { - while (true) { - Object o = connection.getDispatchQueue().poll(timeout, TimeUnit.MILLISECONDS); - - if (o == null) { - return null; - } - if (o instanceof MessageDispatch) { - - MessageDispatch dispatch = (MessageDispatch) o; - if (dispatch.getMessage() == null) { - return null; - } - dispatch.setMessage(dispatch.getMessage().copy()); - dispatch.getMessage().setRedeliveryCounter(dispatch.getRedeliveryCounter()); - return dispatch.getMessage(); - } - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/CheckDuplicateMessagesOnDuplexTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/CheckDuplicateMessagesOnDuplexTest.java deleted file mode 100644 index 7fa257b1f1..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/CheckDuplicateMessagesOnDuplexTest.java +++ /dev/null @@ -1,359 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network; - -import javax.jms.Connection; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.net.ServerSocketFactory; -import java.io.File; -import java.io.IOException; -import java.net.Socket; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.broker.jmx.ManagementContext; -import org.apache.activemq.command.Response; -import org.apache.activemq.store.PersistenceAdapter; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.store.leveldb.LevelDBPersistenceAdapter; -import org.apache.activemq.transport.Transport; -import org.apache.activemq.transport.TransportFilter; -import org.apache.activemq.transport.TransportServer; -import org.apache.activemq.transport.nio.NIOTransport; -import org.apache.activemq.transport.nio.NIOTransportFactory; -import org.apache.activemq.transport.tcp.TcpTransportFactory; -import org.apache.activemq.transport.tcp.TcpTransportServer; -import org.apache.activemq.wireformat.WireFormat; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -/** - * @author x22koe - */ -public class CheckDuplicateMessagesOnDuplexTest { - - private static final Logger log = LoggerFactory.getLogger(CheckDuplicateMessagesOnDuplexTest.class); - private BrokerService localBroker; - private BrokerService remoteBroker; - private ActiveMQConnectionFactory localFactory; - private ActiveMQConnectionFactory remoteFactory; - private Session localSession; - private MessageConsumer consumer; - private Session remoteSession; - private MessageProducer producer; - private Connection remoteConnection; - private Connection localConnection; - private DebugTransportFilter debugTransportFilter; - private boolean useLevelDB = false; - - public CheckDuplicateMessagesOnDuplexTest() { - } - - @BeforeClass - public static void setUpClass() { - } - - @AfterClass - public static void tearDownClass() { - } - - @Before - public void setUp() { - } - - @After - public void tearDown() { - } - - @Test - public void testConnectionLossBehaviorBeforeAckIsSent() throws Exception { - createBrokers(); - localBroker.deleteAllMessages(); - remoteBroker.deleteAllMessages(); - startBrokers(); - openConnections(); - - Thread.sleep(1000); - log.info("\n\n==============================================\nsend hello1\n"); - - // simulate network failure between REMOTE and LOCAL just before the reception response is sent back to REMOTE - debugTransportFilter.closeOnResponse = true; - - producer.send(remoteSession.createTextMessage("hello1")); - Message msg = consumer.receive(30000); - - assertNotNull("expected hello1", msg); - assertEquals("hello1", ((TextMessage) msg).getText()); - - Thread.sleep(1000); - log.info("\n\n------------------------------------------\nsend hello2\n"); - - producer.send(remoteSession.createTextMessage("hello2")); - msg = consumer.receive(30000); - - assertNotNull("expected hello2", msg); - assertEquals("hello2", ((TextMessage) msg).getText()); - - closeLocalConnection(); - - Thread.sleep(1000); - log.info("\n\n------------------------------------------\nsend hello3\n"); - - openLocalConnection(); - - Thread.sleep(1000); - - producer.send(remoteSession.createTextMessage("hello3")); - msg = consumer.receive(30000); - - assertNotNull("expected hello3", msg); - assertEquals("hello3", ((TextMessage) msg).getText()); - - Thread.sleep(1000); - log.info("\n\n==============================================\n\n"); - - closeConnections(); - stopBrokers(); - - // restart the local broker, which should be empty - - Thread.sleep(1000); - log.info("\n\n##############################################\n\n"); - - createLocalBroker(); - startLocalBroker(); - openLocalConnection(); - - // this should not return the "hello1" message - msg = consumer.receive(1000); - - closeLocalConnection(); - stopLocalBroker(); - - assertNull(msg); - } - - private void createBrokers() throws Exception { - createLocalBroker(); - createRemoteBroker(); - } - - private void createLocalBroker() throws Exception { - localBroker = new BrokerService(); - localBroker.setBrokerName("LOCAL"); - localBroker.setUseJmx(true); - localBroker.setSchedulePeriodForDestinationPurge(5000); - ManagementContext managementContext = new ManagementContext(); - managementContext.setCreateConnector(false); - localBroker.setManagementContext(managementContext); - PersistenceAdapter persistenceAdapter = persistenceAdapterFactory("target/local"); - localBroker.setPersistenceAdapter(persistenceAdapter); - List transportConnectors = new ArrayList<>(); - DebugTransportFactory tf = new DebugTransportFactory(); - TransportServer transport = tf.doBind(URI.create("nio://127.0.0.1:23539")); - TransportConnector transportConnector = new TransportConnector(transport); - transportConnector.setName("tc"); - transportConnector.setAuditNetworkProducers(true); - transportConnectors.add(transportConnector); - localBroker.setTransportConnectors(transportConnectors); - } - - private void createRemoteBroker() throws Exception { - remoteBroker = new BrokerService(); - remoteBroker.setBrokerName("REMOTE"); - remoteBroker.setUseJmx(true); - remoteBroker.setSchedulePeriodForDestinationPurge(5000); - ManagementContext managementContext = new ManagementContext(); - managementContext.setCreateConnector(false); - remoteBroker.setManagementContext(managementContext); - PersistenceAdapter persistenceAdapter = persistenceAdapterFactory("target/remote"); - remoteBroker.setPersistenceAdapter(persistenceAdapter); - List networkConnectors = new ArrayList<>(); - DiscoveryNetworkConnector networkConnector = new DiscoveryNetworkConnector(); - networkConnector.setName("to local"); - // set maxInactivityDuration to 0, otherwise the broker restarts while you are in the debugger - networkConnector.setUri(URI.create("static://(tcp://127.0.0.1:23539?wireFormat.maxInactivityDuration=0)")); - networkConnector.setDuplex(true); - //networkConnector.setNetworkTTL(5); - //networkConnector.setDynamicOnly(true); - networkConnector.setAlwaysSyncSend(true); - networkConnector.setDecreaseNetworkConsumerPriority(false); - networkConnector.setPrefetchSize(1); - networkConnector.setCheckDuplicateMessagesOnDuplex(true); - networkConnectors.add(networkConnector); - remoteBroker.setNetworkConnectors(networkConnectors); - } - - private void startBrokers() throws Exception { - startLocalBroker(); - startRemoteBroker(); - } - - private void startLocalBroker() throws Exception { - localBroker.start(); - localBroker.waitUntilStarted(); - } - - private void startRemoteBroker() throws Exception { - remoteBroker.start(); - remoteBroker.waitUntilStarted(); - } - - private void openConnections() throws JMSException { - openLocalConnection(); - openRemoteConnection(); - } - - private void openLocalConnection() throws JMSException { - localFactory = new ActiveMQConnectionFactory(localBroker.getVmConnectorURI()); - //localFactory.setSendAcksAsync(false); - localConnection = localFactory.createConnection(); - localConnection.start(); - localSession = localConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = localSession.createConsumer(localSession.createQueue("testqueue")); - } - - private void openRemoteConnection() throws JMSException { - remoteFactory = new ActiveMQConnectionFactory(remoteBroker.getVmConnectorURI()); - //remoteFactory.setSendAcksAsync(false); - remoteConnection = remoteFactory.createConnection(); - remoteConnection.start(); - remoteSession = remoteConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = remoteSession.createProducer(remoteSession.createQueue("testqueue")); - } - - private void closeConnections() throws JMSException { - closeLocalConnection(); - closeRemoteConnection(); - } - - private void closeLocalConnection() throws JMSException { - localConnection.close(); - } - - private void closeRemoteConnection() throws JMSException { - remoteConnection.close(); - } - - private void stopBrokers() throws Exception { - stopRemoteBroker(); - stopLocalBroker(); - } - - private void stopLocalBroker() throws Exception { - localBroker.stop(); - localBroker.waitUntilStopped(); - } - - private void stopRemoteBroker() throws Exception { - remoteBroker.stop(); - remoteBroker.waitUntilStopped(); - } - - private PersistenceAdapter persistenceAdapterFactory(String path) { - if (useLevelDB) { - return persistenceAdapterFactory_LevelDB(path); - } else { - return persistenceAdapterFactory_KahaDB(path); - } - } - - private PersistenceAdapter persistenceAdapterFactory_KahaDB(String path) { - KahaDBPersistenceAdapter kahaDBPersistenceAdapter = new KahaDBPersistenceAdapter(); - kahaDBPersistenceAdapter.setDirectory(new File(path)); - kahaDBPersistenceAdapter.setIgnoreMissingJournalfiles(true); - kahaDBPersistenceAdapter.setCheckForCorruptJournalFiles(true); - kahaDBPersistenceAdapter.setChecksumJournalFiles(true); - return kahaDBPersistenceAdapter; - } - - private PersistenceAdapter persistenceAdapterFactory_LevelDB(String path) { - LevelDBPersistenceAdapter levelDBPersistenceAdapter = new LevelDBPersistenceAdapter(); - levelDBPersistenceAdapter.setDirectory(new File(path)); - return levelDBPersistenceAdapter; - } - - private class DebugTransportFactory extends NIOTransportFactory { - - @Override - protected TcpTransportServer createTcpTransportServer(URI location, - ServerSocketFactory serverSocketFactory) throws IOException, URISyntaxException { - return new DebugTransportServer(this, location, serverSocketFactory); - } - } - - private class DebugTransportServer extends TcpTransportServer { - - public DebugTransportServer(TcpTransportFactory transportFactory, - URI location, - ServerSocketFactory serverSocketFactory) throws IOException, URISyntaxException { - super(transportFactory, location, serverSocketFactory); - } - - @Override - protected Transport createTransport(Socket socket, WireFormat format) throws IOException { - Transport transport; - transport = new NIOTransport(format, socket); - debugTransportFilter = new DebugTransportFilter(transport); - return debugTransportFilter; - } - } - - private class DebugTransportFilter extends TransportFilter { - - boolean closeOnResponse = false; - - public DebugTransportFilter(Transport next) { - super(next); - } - - @Override - public void oneway(Object command) throws IOException { - if (closeOnResponse && command instanceof Response) { - closeOnResponse = false; - log.warn("\n\nclosing connection before response is sent\n\n"); - try { - ((NIOTransport) next).stop(); - } catch (Exception ex) { - log.error("couldn't stop niotransport", ex); - } - // don't send response - return; - } - super.oneway(command); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/CompressionOverNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/CompressionOverNetworkTest.java deleted file mode 100644 index 19beb7f550..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/CompressionOverNetworkTest.java +++ /dev/null @@ -1,333 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network; - -import javax.jms.BytesMessage; -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.MapMessage; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.StreamMessage; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.UUID; -import java.util.concurrent.ConcurrentMap; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQBytesMessage; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQMapMessage; -import org.apache.activemq.command.ActiveMQObjectMessage; -import org.apache.activemq.command.ActiveMQStreamMessage; -import org.apache.activemq.command.ActiveMQTextMessage; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.command.ConsumerId; -import org.apache.activemq.util.Wait; -import org.apache.activemq.xbean.BrokerFactoryBean; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.support.AbstractApplicationContext; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -public class CompressionOverNetworkTest { - - protected static final int RECEIVE_TIMEOUT_MILLS = 10000; - protected static final int MESSAGE_COUNT = 10; - private static final Logger LOG = LoggerFactory.getLogger(CompressionOverNetworkTest.class); - - protected AbstractApplicationContext context; - protected Connection localConnection; - protected Connection remoteConnection; - protected BrokerService localBroker; - protected BrokerService remoteBroker; - protected Session localSession; - protected Session remoteSession; - protected ActiveMQDestination included; - - @Test - public void testCompressedOverCompressedNetwork() throws Exception { - - ActiveMQConnection localAmqConnection = (ActiveMQConnection) localConnection; - localAmqConnection.setUseCompression(true); - - MessageConsumer consumer1 = remoteSession.createConsumer(included); - MessageProducer producer = localSession.createProducer(included); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - - waitForConsumerRegistration(localBroker, 1, included); - - StringBuilder payload = new StringBuilder("test-"); - for (int i = 0; i < 100; ++i) { - payload.append(UUID.randomUUID().toString()); - } - - Message test = localSession.createTextMessage(payload.toString()); - producer.send(test); - Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS); - assertNotNull(msg); - ActiveMQTextMessage message = (ActiveMQTextMessage) msg; - assertTrue(message.isCompressed()); - assertEquals(payload.toString(), message.getText()); - } - - @Test - public void testTextMessageCompression() throws Exception { - - MessageConsumer consumer1 = remoteSession.createConsumer(included); - MessageProducer producer = localSession.createProducer(included); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - - waitForConsumerRegistration(localBroker, 1, included); - - StringBuilder payload = new StringBuilder("test-"); - for (int i = 0; i < 100; ++i) { - payload.append(UUID.randomUUID().toString()); - } - - Message test = localSession.createTextMessage(payload.toString()); - producer.send(test); - Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS); - assertNotNull(msg); - ActiveMQTextMessage message = (ActiveMQTextMessage) msg; - assertTrue(message.isCompressed()); - assertEquals(payload.toString(), message.getText()); - } - - @Test - public void testBytesMessageCompression() throws Exception { - - MessageConsumer consumer1 = remoteSession.createConsumer(included); - MessageProducer producer = localSession.createProducer(included); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - - waitForConsumerRegistration(localBroker, 1, included); - - StringBuilder payload = new StringBuilder("test-"); - for (int i = 0; i < 100; ++i) { - payload.append(UUID.randomUUID().toString()); - } - - byte[] bytes = payload.toString().getBytes(StandardCharsets.UTF_8); - - BytesMessage test = localSession.createBytesMessage(); - test.writeBytes(bytes); - producer.send(test); - Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS); - assertNotNull(msg); - ActiveMQBytesMessage message = (ActiveMQBytesMessage) msg; - assertTrue(message.isCompressed()); - assertTrue(message.getContent().getLength() < bytes.length); - - byte[] result = new byte[bytes.length]; - assertEquals(bytes.length, message.readBytes(result)); - assertEquals(-1, message.readBytes(result)); - - for (int i = 0; i < bytes.length; ++i) { - assertEquals(bytes[i], result[i]); - } - } - - @Test - public void testStreamMessageCompression() throws Exception { - - MessageConsumer consumer1 = remoteSession.createConsumer(included); - MessageProducer producer = localSession.createProducer(included); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - - waitForConsumerRegistration(localBroker, 1, included); - - StreamMessage test = localSession.createStreamMessage(); - - for (int i = 0; i < 100; ++i) { - test.writeString("test string: " + i); - } - - producer.send(test); - Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS); - assertNotNull(msg); - ActiveMQStreamMessage message = (ActiveMQStreamMessage) msg; - assertTrue(message.isCompressed()); - - for (int i = 0; i < 100; ++i) { - assertEquals("test string: " + i, message.readString()); - } - } - - @Test - public void testMapMessageCompression() throws Exception { - - MessageConsumer consumer1 = remoteSession.createConsumer(included); - MessageProducer producer = localSession.createProducer(included); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - - waitForConsumerRegistration(localBroker, 1, included); - - MapMessage test = localSession.createMapMessage(); - - for (int i = 0; i < 100; ++i) { - test.setString(Integer.toString(i), "test string: " + i); - } - - producer.send(test); - Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS); - assertNotNull(msg); - ActiveMQMapMessage message = (ActiveMQMapMessage) msg; - assertTrue(message.isCompressed()); - - for (int i = 0; i < 100; ++i) { - assertEquals("test string: " + i, message.getString(Integer.toString(i))); - } - } - - @Test - public void testObjectMessageCompression() throws Exception { - - MessageConsumer consumer1 = remoteSession.createConsumer(included); - MessageProducer producer = localSession.createProducer(included); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - - waitForConsumerRegistration(localBroker, 1, included); - - StringBuilder payload = new StringBuilder("test-"); - for (int i = 0; i < 100; ++i) { - payload.append(UUID.randomUUID().toString()); - } - - Message test = localSession.createObjectMessage(payload.toString()); - producer.send(test); - Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS); - assertNotNull(msg); - ActiveMQObjectMessage message = (ActiveMQObjectMessage) msg; - assertTrue(message.isCompressed()); - assertEquals(payload.toString(), message.getObject()); - } - - private void waitForConsumerRegistration(final BrokerService brokerService, - final int min, - final ActiveMQDestination destination) throws Exception { - assertTrue("Internal bridge consumers registered in time", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Object[] bridges = brokerService.getNetworkConnectors().get(0).bridges.values().toArray(); - if (bridges.length > 0) { - LOG.info(brokerService + " bridges " + Arrays.toString(bridges)); - DemandForwardingBridgeSupport demandForwardingBridgeSupport = (DemandForwardingBridgeSupport) bridges[0]; - ConcurrentMap forwardingBridges = demandForwardingBridgeSupport.getLocalSubscriptionMap(); - - LOG.info(brokerService + " bridge " + demandForwardingBridgeSupport + ", localSubs: " + forwardingBridges); - if (!forwardingBridges.isEmpty()) { - for (DemandSubscription demandSubscription : forwardingBridges.values()) { - if (demandSubscription.getLocalInfo().getDestination().equals(destination)) { - LOG.info(brokerService + " DemandSubscription " + demandSubscription + ", size: " + demandSubscription.size()); - return demandSubscription.size() >= min; - } - } - } - } - return false; - } - })); - } - - @Before - public void setUp() throws Exception { - doSetUp(true); - } - - @After - public void tearDown() throws Exception { - doTearDown(); - } - - protected void doTearDown() throws Exception { - localConnection.close(); - remoteConnection.close(); - localBroker.stop(); - remoteBroker.stop(); - } - - protected void doSetUp(boolean deleteAllMessages) throws Exception { - localBroker = createLocalBroker(); - localBroker.setDeleteAllMessagesOnStartup(deleteAllMessages); - localBroker.start(); - localBroker.waitUntilStarted(); - remoteBroker = createRemoteBroker(); - remoteBroker.setDeleteAllMessagesOnStartup(deleteAllMessages); - remoteBroker.start(); - remoteBroker.waitUntilStarted(); - URI localURI = localBroker.getVmConnectorURI(); - ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(localURI); - fac.setAlwaysSyncSend(true); - fac.setDispatchAsync(false); - localConnection = fac.createConnection(); - localConnection.setClientID("clientId"); - localConnection.start(); - URI remoteURI = remoteBroker.getVmConnectorURI(); - fac = new ActiveMQConnectionFactory(remoteURI); - remoteConnection = fac.createConnection(); - remoteConnection.setClientID("clientId"); - remoteConnection.start(); - included = new ActiveMQTopic("include.test.bar"); - localSession = localConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - remoteSession = remoteConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } - - protected String getRemoteBrokerURI() { - return "org/apache/activemq/network/remoteBroker.xml"; - } - - protected String getLocalBrokerURI() { - return "org/apache/activemq/network/localBroker.xml"; - } - - protected BrokerService createBroker(String uri) throws Exception { - Resource resource = new ClassPathResource(uri); - BrokerFactoryBean factory = new BrokerFactoryBean(resource); - resource = new ClassPathResource(uri); - factory = new BrokerFactoryBean(resource); - factory.afterPropertiesSet(); - BrokerService result = factory.getBroker(); - - for (NetworkConnector connector : result.getNetworkConnectors()) { - connector.setUseCompression(true); - } - - return result; - } - - protected BrokerService createLocalBroker() throws Exception { - return createBroker(getLocalBrokerURI()); - } - - protected BrokerService createRemoteBroker() throws Exception { - return createBroker(getRemoteBrokerURI()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DemandForwardingBridgeFilterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DemandForwardingBridgeFilterTest.java deleted file mode 100644 index 164e01adec..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DemandForwardingBridgeFilterTest.java +++ /dev/null @@ -1,194 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network; - -import java.util.Arrays; - -import junit.framework.Test; - -import org.apache.activemq.broker.StubConnection; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ConnectionInfo; -import org.apache.activemq.command.ConsumerInfo; -import org.apache.activemq.command.Message; -import org.apache.activemq.command.ProducerInfo; -import org.apache.activemq.command.SessionInfo; - -public class DemandForwardingBridgeFilterTest extends NetworkTestSupport { - - private DemandForwardingBridge bridge; - - private StubConnection producerConnection; - - private ProducerInfo producerInfo; - - private StubConnection consumerConnection; - - private SessionInfo consumerSessionInfo; - - public void testWildcardOnExcludedDestination() throws Exception { - - NetworkBridgeConfiguration configuration = getDefaultBridgeConfiguration(); - - configuration.setExcludedDestinations(Arrays.asList(ActiveMQDestination.createDestination("OTHER.>", ActiveMQDestination.TOPIC_TYPE))); - configuration.setDynamicallyIncludedDestinations(Arrays.asList(ActiveMQDestination.createDestination("TEST", ActiveMQDestination.QUEUE_TYPE))); - - configureAndStartBridge(configuration); - - assertReceiveMessageOn("TEST", ActiveMQDestination.QUEUE_TYPE); - assertReceiveNoMessageOn("OTHER.T1", ActiveMQDestination.TOPIC_TYPE); - } - - public void testWildcardOnTwoExcludedDestination() throws Exception { - NetworkBridgeConfiguration configuration = getDefaultBridgeConfiguration(); - - configuration.setExcludedDestinations(Arrays.asList(ActiveMQDestination.createDestination("OTHER.>", ActiveMQDestination.QUEUE_TYPE), ActiveMQDestination.createDestination("TEST.X1", ActiveMQDestination.QUEUE_TYPE))); - configuration.setDynamicallyIncludedDestinations(Arrays.asList(ActiveMQDestination.createDestination("TEST.X2", ActiveMQDestination.QUEUE_TYPE))); - - configureAndStartBridge(configuration); - - assertReceiveMessageOn("TEST.X2", ActiveMQDestination.QUEUE_TYPE); - assertReceiveNoMessageOn("OTHER.X1", ActiveMQDestination.QUEUE_TYPE); - assertReceiveNoMessageOn("TEST.X1", ActiveMQDestination.QUEUE_TYPE); - } - - public void testWildcardOnDynamicallyIncludedDestination() throws Exception { - - NetworkBridgeConfiguration configuration = getDefaultBridgeConfiguration(); - - configuration.setDynamicallyIncludedDestinations(Arrays.asList(ActiveMQDestination.createDestination("OTHER.>", ActiveMQDestination.QUEUE_TYPE), ActiveMQDestination.createDestination("TEST.X2", ActiveMQDestination.QUEUE_TYPE))); - - configureAndStartBridge(configuration); - - assertReceiveMessageOn("OTHER.X1", ActiveMQDestination.QUEUE_TYPE); - assertReceiveMessageOn("TEST.X2", ActiveMQDestination.QUEUE_TYPE); - } - - public void testDistinctTopicAndQueue() throws Exception { - - NetworkBridgeConfiguration configuration = getDefaultBridgeConfiguration(); - - configuration.setExcludedDestinations(Arrays.asList(ActiveMQDestination.createDestination(">", ActiveMQDestination.TOPIC_TYPE))); - configuration.setDynamicallyIncludedDestinations(Arrays.asList(ActiveMQDestination.createDestination(">", ActiveMQDestination.QUEUE_TYPE))); - - configureAndStartBridge(configuration); - - assertReceiveMessageOn("TEST", ActiveMQDestination.QUEUE_TYPE); - assertReceiveNoMessageOn("TEST", ActiveMQDestination.TOPIC_TYPE); - } - - public void testListOfExcludedDestinationWithWildcard() throws Exception { - - NetworkBridgeConfiguration configuration = getDefaultBridgeConfiguration(); - - configuration.setExcludedDestinations(Arrays.asList(ActiveMQDestination.createDestination("OTHER.>", ActiveMQDestination.TOPIC_TYPE), ActiveMQDestination.createDestination("TEST.*", ActiveMQDestination.TOPIC_TYPE))); - configuration.setDynamicallyIncludedDestinations(Arrays.asList(ActiveMQDestination.createDestination("TEST.X1", ActiveMQDestination.QUEUE_TYPE))); - - configureAndStartBridge(configuration); - - assertReceiveMessageOn("TEST.X1", ActiveMQDestination.QUEUE_TYPE); - assertReceiveNoMessageOn("OTHER.T1", ActiveMQDestination.TOPIC_TYPE); - assertReceiveNoMessageOn("OTHER.T2", ActiveMQDestination.TOPIC_TYPE); - } - - private void assertReceiveMessageOn(String destinationName, - byte destinationType) throws Exception, InterruptedException { - - ActiveMQDestination destination = ActiveMQDestination.createDestination(destinationName, destinationType); - - // Send the message to the local broker. - producerConnection.send(createMessage(producerInfo, destination, destinationType)); - - // Make sure the message was delivered via the remote. - Message m = createConsumerAndReceiveMessage(destination); - - assertNotNull(m); - } - - private void assertReceiveNoMessageOn(String destinationName, - byte destinationType) throws Exception, InterruptedException { - - ActiveMQDestination destination = ActiveMQDestination.createDestination(destinationName, destinationType); - - // Send the message to the local broker. - producerConnection.send(createMessage(producerInfo, destination, destinationType)); - - // Make sure the message was delivered via the remote. - Message m = createConsumerAndReceiveMessage(destination); - assertNull(m); - } - - private Message createConsumerAndReceiveMessage(ActiveMQDestination destination) throws Exception { - // Now create remote consumer that should cause message to move to this - // remote consumer. - ConsumerInfo consumerInfo = createConsumerInfo(consumerSessionInfo, destination); - consumerConnection.send(consumerInfo); - - Message m = receiveMessage(consumerConnection); - return m; - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - - producerConnection = createConnection(); - ConnectionInfo producerConnectionInfo = createConnectionInfo(); - SessionInfo producerSessionInfo = createSessionInfo(producerConnectionInfo); - producerInfo = createProducerInfo(producerSessionInfo); - producerConnection.send(producerConnectionInfo); - producerConnection.send(producerSessionInfo); - producerConnection.send(producerInfo); - - consumerConnection = createRemoteConnection(); - ConnectionInfo consumerConnectionInfo = createConnectionInfo(); - consumerSessionInfo = createSessionInfo(consumerConnectionInfo); - consumerConnection.send(consumerConnectionInfo); - consumerConnection.send(consumerSessionInfo); - } - - @Override - protected void tearDown() throws Exception { - bridge.stop(); - super.tearDown(); - } - - public static Test suite() { - return suite(DemandForwardingBridgeFilterTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - public NetworkBridgeConfiguration getDefaultBridgeConfiguration() { - NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); - config.setBrokerName("local"); - config.setDispatchAsync(false); - return config; - } - - private void configureAndStartBridge(NetworkBridgeConfiguration configuration) throws Exception { - bridge = new DemandForwardingBridge(configuration, createTransport(), createRemoteTransport()); - bridge.setBrokerService(broker); - bridge.setDynamicallyIncludedDestinations(configuration.getDynamicallyIncludedDestinations().toArray(new ActiveMQDestination[configuration.getDynamicallyIncludedDestinations().size()])); - bridge.setExcludedDestinations(configuration.getExcludedDestinations().toArray(new ActiveMQDestination[configuration.getExcludedDestinations().size()])); - bridge.setStaticallyIncludedDestinations(configuration.getStaticallyIncludedDestinations().toArray(new ActiveMQDestination[configuration.getStaticallyIncludedDestinations().size()])); - bridge.start(); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DemandForwardingBridgeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DemandForwardingBridgeTest.java deleted file mode 100644 index 38ff0507b5..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DemandForwardingBridgeTest.java +++ /dev/null @@ -1,177 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network; - -import javax.jms.DeliveryMode; - -import junit.framework.Test; - -import org.apache.activemq.broker.StubConnection; -import org.apache.activemq.broker.region.DestinationStatistics; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ConnectionInfo; -import org.apache.activemq.command.ConsumerInfo; -import org.apache.activemq.command.Message; -import org.apache.activemq.command.MessageAck; -import org.apache.activemq.command.ProducerInfo; -import org.apache.activemq.command.SessionInfo; -import org.apache.activemq.util.Wait; - -public class DemandForwardingBridgeTest extends NetworkTestSupport { - - public ActiveMQDestination destination; - public byte destinationType; - public int deliveryMode; - private DemandForwardingBridge bridge; - - public void initCombosForTestSendThenAddConsumer() { - addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE)}); - } - - public void testSendThenAddConsumer() throws Exception { - - // Start a producer on local broker - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo); - - destination = createDestinationInfo(connection1, connectionInfo1, destinationType); - - // Start a consumer on a remote broker - final StubConnection connection2 = createRemoteConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - - // Send the message to the local broker. - connection1.send(createMessage(producerInfo, destination, deliveryMode)); - - // Verify that the message stayed on the local broker. - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - connection1.send(consumerInfo1); - Message m = receiveMessage(connection1); - assertNotNull(m); - // Close consumer to cause the message to rollback. - connection1.send(consumerInfo1.createRemoveCommand()); - - final DestinationStatistics destinationStatistics = broker.getDestination(destination).getDestinationStatistics(); - assertEquals("broker dest stat dispatched", 1, destinationStatistics.getDispatched().getCount()); - assertEquals("broker dest stat dequeues", 0, destinationStatistics.getDequeues().getCount()); - assertEquals("broker dest stat forwards", 0, destinationStatistics.getForwards().getCount()); - - // Now create remote consumer that should cause message to move to this - // remote consumer. - final ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - connection2.request(consumerInfo2); - - // Make sure the message was delivered via the remote. - assertTrue("message was received", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message msg = receiveMessage(connection2); - if (msg != null) { - connection2.request(createAck(consumerInfo2, msg, 1, MessageAck.STANDARD_ACK_TYPE)); - return true; - } - - return false; - } - })); - - assertTrue("broker dest stat forwards", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 1 == destinationStatistics.getForwards().getCount(); - } - })); - - assertEquals("broker dest stat dequeues", 1, destinationStatistics.getDequeues().getCount()); - } - - public void initCombosForTestAddConsumerThenSend() { - addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); - } - - public void testAddConsumerThenSend() throws Exception { - - // Start a producer on local broker - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo); - - destination = createDestinationInfo(connection1, connectionInfo1, destinationType); - - // Start a consumer on a remote broker - StubConnection connection2 = createRemoteConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo2, destination); - connection2.send(consumerInfo); - - // Give demand forwarding bridge a chance to finish forwarding the - // subscriptions. - try { - Thread.sleep(1000); - } catch (InterruptedException ie) { - ie.printStackTrace(); - } - - // Send the message to the local boker. - connection1.request(createMessage(producerInfo, destination, deliveryMode)); - // Make sure the message was delivered via the remote. - receiveMessage(connection2); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); - config.setBrokerName("local"); - config.setDispatchAsync(false); - bridge = new DemandForwardingBridge(config, createTransport(), createRemoteTransport()); - bridge.setBrokerService(broker); - bridge.start(); - } - - @Override - protected void tearDown() throws Exception { - bridge.stop(); - super.tearDown(); - } - - public static Test suite() { - return suite(DemandForwardingBridgeTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DuplexNetworkMBeanTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DuplexNetworkMBeanTest.java deleted file mode 100644 index eb0773f51f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DuplexNetworkMBeanTest.java +++ /dev/null @@ -1,167 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network; - -import javax.management.ObjectName; -import java.net.MalformedURLException; -import java.util.Set; - -import org.apache.activemq.broker.BrokerService; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assume.assumeNotNull; - -public class DuplexNetworkMBeanTest { - - protected static final Logger LOG = LoggerFactory.getLogger(DuplexNetworkMBeanTest.class); - protected final int numRestarts = 3; - - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("broker"); - broker.addConnector("tcp://localhost:61617?transport.reuseAddress=true"); - - return broker; - } - - protected BrokerService createNetworkedBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("networkedBroker"); - broker.addConnector("tcp://localhost:62617?transport.reuseAddress=true"); - NetworkConnector networkConnector = broker.addNetworkConnector("static:(tcp://localhost:61617?wireFormat.maxInactivityDuration=500)?useExponentialBackOff=false"); - networkConnector.setDuplex(true); - return broker; - } - - @Test - public void testMbeanPresenceOnNetworkBrokerRestart() throws Exception { - BrokerService broker = createBroker(); - try { - broker.start(); - assertEquals(1, countMbeans(broker, "connector", 30000)); - assertEquals(0, countMbeans(broker, "connectionName")); - BrokerService networkedBroker = null; - for (int i = 0; i < numRestarts; i++) { - networkedBroker = createNetworkedBroker(); - try { - networkedBroker.start(); - assertEquals(1, countMbeans(networkedBroker, "networkBridge", 2000)); - assertEquals(1, countMbeans(broker, "networkBridge", 2000)); - assertEquals(2, countMbeans(broker, "connectionName")); - } finally { - networkedBroker.stop(); - networkedBroker.waitUntilStopped(); - } - assertEquals(0, countMbeans(networkedBroker, "stopped")); - assertEquals(0, countMbeans(broker, "networkBridge")); - } - - assertEquals(0, countMbeans(networkedBroker, "networkBridge")); - assertEquals(0, countMbeans(networkedBroker, "connector")); - assertEquals(0, countMbeans(networkedBroker, "connectionName")); - assertEquals(1, countMbeans(broker, "connector")); - } finally { - broker.stop(); - broker.waitUntilStopped(); - } - } - - @Test - public void testMbeanPresenceOnBrokerRestart() throws Exception { - - BrokerService networkedBroker = createNetworkedBroker(); - try { - networkedBroker.start(); - assertEquals(1, countMbeans(networkedBroker, "connector=networkConnectors", 30000)); - assertEquals(0, countMbeans(networkedBroker, "connectionName")); - - BrokerService broker = null; - for (int i = 0; i < numRestarts; i++) { - broker = createBroker(); - try { - broker.start(); - assertEquals(1, countMbeans(networkedBroker, "networkBridge", 5000)); - assertEquals("restart number: " + i, 2, countMbeans(broker, "connectionName", 10000)); - } finally { - broker.stop(); - broker.waitUntilStopped(); - } - assertEquals(0, countMbeans(broker, "stopped")); - } - - assertEquals(1, countMbeans(networkedBroker, "connector=networkConnectors")); - assertEquals(0, countMbeans(networkedBroker, "connectionName")); - assertEquals(0, countMbeans(broker, "connectionName")); - } finally { - networkedBroker.stop(); - networkedBroker.waitUntilStopped(); - } - } - - private int countMbeans(BrokerService broker, String type) throws Exception { - return countMbeans(broker, type, 0); - } - - private int countMbeans(BrokerService broker, String type, int timeout) throws Exception { - final long expiryTime = System.currentTimeMillis() + timeout; - - if (!type.contains("=")) { - type = type + "=*"; - } - - final ObjectName beanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=" + broker.getBrokerName() + "," + type + ",*"); - Set mbeans = null; - int count = 0; - do { - if (timeout > 0) { - Thread.sleep(100); - } - - LOG.info("Query name: " + beanName); - mbeans = broker.getManagementContext().queryNames(beanName, null); - if (mbeans != null) { - count = mbeans.size(); - } else { - logAllMbeans(broker); - } - } while ((mbeans == null || mbeans.isEmpty()) && expiryTime > System.currentTimeMillis()); - - // If port 1099 is in use when the Broker starts, starting the jmx connector - // will fail. So, if we have no mbsc to query, skip the test. - if (timeout > 0) { - assumeNotNull(mbeans); - } - - return count; - } - - private void logAllMbeans(BrokerService broker) throws MalformedURLException { - try { - // trace all existing MBeans - Set all = broker.getManagementContext().queryNames(null, null); - LOG.info("Total MBean count=" + all.size()); - for (ObjectName on : all) { - LOG.info(on.toString()); - } - } catch (Exception ignored) { - LOG.warn("getMBeanServer ex: " + ignored); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DuplexNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DuplexNetworkTest.java deleted file mode 100644 index 1f89eca86f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DuplexNetworkTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network; - -import javax.jms.MessageProducer; -import javax.jms.TemporaryQueue; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.util.Wait; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class DuplexNetworkTest extends SimpleNetworkTest { - - @Override - protected String getLocalBrokerURI() { - return "org/apache/activemq/network/duplexLocalBroker.xml"; - } - - @Override - protected BrokerService createRemoteBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("remoteBroker"); - broker.addConnector("tcp://localhost:61617"); - return broker; - } - - @Test - public void testTempQueues() throws Exception { - TemporaryQueue temp = localSession.createTemporaryQueue(); - MessageProducer producer = localSession.createProducer(temp); - producer.send(localSession.createTextMessage("test")); - Thread.sleep(100); - assertEquals("Destination not created", 1, remoteBroker.getAdminView().getTemporaryQueues().length); - temp.delete(); - - assertTrue("Destination not deleted", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 0 == remoteBroker.getAdminView().getTemporaryQueues().length; - } - })); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DynamicallyIncludedDestinationsDuplexNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DynamicallyIncludedDestinationsDuplexNetworkTest.java deleted file mode 100644 index 2d6544562b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/DynamicallyIncludedDestinationsDuplexNetworkTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network; - -import javax.jms.MessageProducer; -import javax.jms.TemporaryQueue; -import java.lang.reflect.Field; -import java.util.concurrent.CopyOnWriteArrayList; - -import org.apache.activemq.advisory.AdvisorySupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnection; -import org.apache.activemq.broker.TransportConnector; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; - -/** - * @author Christian Posta - */ -public class DynamicallyIncludedDestinationsDuplexNetworkTest extends SimpleNetworkTest { - - private static final int REMOTE_BROKER_TCP_PORT = 61617; - - @Override - protected String getLocalBrokerURI() { - return "org/apache/activemq/network/duplexDynamicIncludedDestLocalBroker.xml"; - } - - @Override - protected BrokerService createRemoteBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("remoteBroker"); - broker.addConnector("tcp://localhost:" + REMOTE_BROKER_TCP_PORT); - return broker; - } - - // we have to override this, because with dynamicallyIncludedDestinations working properly - // (see https://issues.apache.org/jira/browse/AMQ-4209) you can't get request/response - // with temps working (there is no wild card like there is for staticallyIncludedDest) - // - @Override - public void testRequestReply() throws Exception { - - } - - @Test - public void testTempQueues() throws Exception { - TemporaryQueue temp = localSession.createTemporaryQueue(); - MessageProducer producer = localSession.createProducer(temp); - producer.send(localSession.createTextMessage("test")); - Thread.sleep(100); - assertEquals("Destination not created", 1, remoteBroker.getAdminView().getTemporaryQueues().length); - temp.delete(); - Thread.sleep(100); - assertEquals("Destination not deleted", 0, remoteBroker.getAdminView().getTemporaryQueues().length); - } - - @Test - public void testDynamicallyIncludedDestinationsForDuplex() throws Exception { - // Once the bridge is set up, we should see the filter used for the duplex end of the bridge - // only subscribe to the specific destinations included in the list - // so let's test that the filter is correct, let's also test the subscription on the localbroker - // is correct - - // the bridge on the remote broker has the correct filter - TransportConnection bridgeConnection = getDuplexBridgeConnectionFromRemote(); - assertNotNull(bridgeConnection); - DemandForwardingBridge duplexBridge = getDuplexBridgeFromConnection(bridgeConnection); - assertNotNull(duplexBridge); - NetworkBridgeConfiguration configuration = getConfigurationFromNetworkBridge(duplexBridge); - assertNotNull(configuration); - assertFalse("This destinationFilter does not include ONLY the destinations specified in dynamicallyIncludedDestinations", configuration.getDestinationFilter().equals(AdvisorySupport.CONSUMER_ADVISORY_TOPIC_PREFIX + ">")); - assertEquals("There are other patterns in the destinationFilter that shouldn't be there", "ActiveMQ.Advisory.Consumer.Queue.include.test.foo,ActiveMQ.Advisory.Consumer.Topic.include.test.bar", configuration.getDestinationFilter()); - } - - private NetworkBridgeConfiguration getConfigurationFromNetworkBridge(DemandForwardingBridgeSupport duplexBridge) throws NoSuchFieldException, IllegalAccessException { - Field f = DemandForwardingBridgeSupport.class.getDeclaredField("configuration"); - f.setAccessible(true); - NetworkBridgeConfiguration configuration = (NetworkBridgeConfiguration) f.get(duplexBridge); - return configuration; - } - - private DemandForwardingBridge getDuplexBridgeFromConnection(TransportConnection bridgeConnection) throws NoSuchFieldException, IllegalAccessException { - Field f = TransportConnection.class.getDeclaredField("duplexBridge"); - f.setAccessible(true); - DemandForwardingBridge bridge = (DemandForwardingBridge) f.get(bridgeConnection); - return bridge; - } - - public TransportConnection getDuplexBridgeConnectionFromRemote() { - TransportConnector transportConnector = remoteBroker.getTransportConnectorByScheme("tcp"); - CopyOnWriteArrayList transportConnections = transportConnector.getConnections(); - TransportConnection duplexBridgeConnectionFromRemote = transportConnections.get(0); - return duplexBridgeConnectionFromRemote; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/FailoverStaticNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/FailoverStaticNetworkTest.java deleted file mode 100644 index 49dc7f863e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/FailoverStaticNetworkTest.java +++ /dev/null @@ -1,467 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.Session; -import javax.management.ObjectName; -import javax.net.ssl.KeyManager; -import javax.net.ssl.TrustManager; -import java.net.URI; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.Vector; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.SslContext; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.transport.tcp.SslBrokerServiceTest; -import org.apache.activemq.util.IntrospectionSupport; -import org.apache.activemq.util.JMXSupport; -import org.apache.activemq.util.Wait; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class FailoverStaticNetworkTest { - - protected static final Logger LOG = LoggerFactory.getLogger(FailoverStaticNetworkTest.class); - - private final static String DESTINATION_NAME = "testQ"; - protected BrokerService brokerA; - protected BrokerService brokerA1; - protected BrokerService brokerB; - protected BrokerService brokerC; - - private SslContext sslContext; - - protected BrokerService createBroker(String scheme, String listenPort, String[] networkToPorts) throws Exception { - return createBroker(scheme, listenPort, networkToPorts, null); - } - - protected BrokerService createBroker(String scheme, - String listenPort, - String[] networkToPorts, - HashMap networkProps) throws Exception { - BrokerService broker = new BrokerService(); - broker.getManagementContext().setCreateConnector(false); - broker.setSslContext(sslContext); - broker.setDeleteAllMessagesOnStartup(true); - broker.setBrokerName("Broker_" + listenPort); - // lazy init listener on broker start - TransportConnector transportConnector = new TransportConnector(); - transportConnector.setUri(new URI(scheme + "://localhost:" + listenPort)); - List transportConnectors = new ArrayList<>(); - transportConnectors.add(transportConnector); - broker.setTransportConnectors(transportConnectors); - if (networkToPorts != null && networkToPorts.length > 0) { - StringBuilder builder = new StringBuilder("static:(failover:(" + scheme + "://localhost:"); - builder.append(networkToPorts[0]); - for (int i = 1; i < networkToPorts.length; i++) { - builder.append("," + scheme + "://localhost:" + networkToPorts[i]); - } - // limit the reconnects in case of initial random connection to slave - // leaving randomize on verifies that this config is picked up - builder.append(")?maxReconnectAttempts=0)?useExponentialBackOff=false"); - NetworkConnector nc = broker.addNetworkConnector(builder.toString()); - if (networkProps != null) { - IntrospectionSupport.setProperties(nc, networkProps); - } - } - return broker; - } - - private BrokerService createBroker(String listenPort, String dataDir) throws Exception { - BrokerService broker = new BrokerService(); - broker.setUseJmx(false); - broker.getManagementContext().setCreateConnector(false); - broker.setBrokerName("Broker_Shared"); - // lazy create transport connector on start completion - TransportConnector connector = new TransportConnector(); - connector.setUri(new URI("tcp://localhost:" + listenPort)); - broker.addConnector(connector); - broker.setDataDirectory(dataDir); - return broker; - } - - @Before - public void setUp() throws Exception { - KeyManager[] km = SslBrokerServiceTest.getKeyManager(); - TrustManager[] tm = SslBrokerServiceTest.getTrustManager(); - sslContext = new SslContext(km, tm, null); - } - - @After - public void tearDown() throws Exception { - brokerB.stop(); - brokerB.waitUntilStopped(); - - brokerA.stop(); - brokerA.waitUntilStopped(); - - if (brokerA1 != null) { - brokerA1.stop(); - brokerA1.waitUntilStopped(); - } - - if (brokerC != null) { - brokerC.stop(); - brokerC.waitUntilStopped(); - } - } - - @Test - public void testSendReceiveAfterReconnect() throws Exception { - brokerA = createBroker("tcp", "61617", null); - brokerA.start(); - brokerB = createBroker("tcp", "62617", new String[]{"61617"}); - brokerB.start(); - doTestNetworkSendReceive(); - - LOG.info("stopping brokerA"); - brokerA.stop(); - brokerA.waitUntilStopped(); - - LOG.info("restarting brokerA"); - brokerA = createBroker("tcp", "61617", null); - brokerA.start(); - - doTestNetworkSendReceive(); - } - - @Test - public void testSendReceiveFailover() throws Exception { - brokerA = createBroker("tcp", "61617", null); - brokerA.start(); - brokerB = createBroker("tcp", "62617", new String[]{"61617", "63617"}); - brokerB.start(); - doTestNetworkSendReceive(); - - // check mbean - Set bridgeNames = getNetworkBridgeMBeanName(brokerB); - assertEquals("only one bridgeName: " + bridgeNames, 1, bridgeNames.size()); - - LOG.info("stopping brokerA"); - brokerA.stop(); - brokerA.waitUntilStopped(); - - LOG.info("restarting brokerA"); - brokerA = createBroker("tcp", "63617", null); - brokerA.start(); - - doTestNetworkSendReceive(); - - Set otherBridgeNames = getNetworkBridgeMBeanName(brokerB); - assertEquals("only one bridgeName: " + otherBridgeNames, 1, otherBridgeNames.size()); - - assertTrue("there was an addition", bridgeNames.addAll(otherBridgeNames)); - } - - private Set getNetworkBridgeMBeanName(BrokerService brokerB) throws Exception { - Set names = new HashSet<>(); - for (ObjectName objectName : brokerB.getManagementContext().queryNames(null, null)) { - if (objectName.getKeyProperty("networkBridge") != null) { - names.add(objectName.getKeyProperty("networkBridge")); - } - } - return names; - } - - @Test - public void testSendReceiveFailoverDuplex() throws Exception { - final Vector errors = new Vector<>(); - final String dataDir = "target/data/shared"; - brokerA = createBroker("61617", dataDir); - brokerA.start(); - - final BrokerService slave = createBroker("63617", dataDir); - brokerA1 = slave; - ExecutorService executor = Executors.newCachedThreadPool(); - executor.execute(new Runnable() { - @Override - public void run() { - try { - slave.start(); - } catch (Exception e) { - e.printStackTrace(); - errors.add(e); - } - } - }); - executor.shutdown(); - - HashMap networkConnectorProps = new HashMap<>(); - networkConnectorProps.put("duplex", "true"); - brokerB = createBroker("tcp", "62617", new String[]{"61617", "63617"}, networkConnectorProps); - brokerB.start(); - - doTestNetworkSendReceive(brokerA, brokerB); - doTestNetworkSendReceive(brokerB, brokerA); - - LOG.info("stopping brokerA (master shared_broker)"); - brokerA.stop(); - brokerA.waitUntilStopped(); - - // wait for slave to start - brokerA1.waitUntilStarted(); - - doTestNetworkSendReceive(brokerA1, brokerB); - doTestNetworkSendReceive(brokerB, brokerA1); - - assertTrue("No unexpected exceptions " + errors, errors.isEmpty()); - } - - @Test - // master slave piggy in the middle setup - public void testSendReceiveFailoverDuplexWithPIM() throws Exception { - final String dataDir = "target/data/shared/pim"; - brokerA = createBroker("61617", dataDir); - brokerA.start(); - - final BrokerService slave = createBroker("63617", dataDir); - brokerA1 = slave; - ExecutorService executor = Executors.newCachedThreadPool(); - executor.execute(new Runnable() { - @Override - public void run() { - try { - slave.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - executor.shutdown(); - - HashMap networkConnectorProps = new HashMap<>(); - networkConnectorProps.put("duplex", "true"); - networkConnectorProps.put("networkTTL", "2"); - - brokerB = createBroker("tcp", "62617", new String[]{"61617", "63617"}, networkConnectorProps); - brokerB.start(); - - assertTrue("all props applied", networkConnectorProps.isEmpty()); - networkConnectorProps.put("duplex", "true"); - networkConnectorProps.put("networkTTL", "2"); - - brokerC = createBroker("tcp", "64617", new String[]{"61617", "63617"}, networkConnectorProps); - brokerC.start(); - assertTrue("all props applied a second time", networkConnectorProps.isEmpty()); - - doTestNetworkSendReceive(brokerC, brokerB); - doTestNetworkSendReceive(brokerB, brokerC); - - LOG.info("stopping brokerA (master shared_broker)"); - brokerA.stop(); - brokerA.waitUntilStopped(); - - doTestNetworkSendReceive(brokerC, brokerB); - doTestNetworkSendReceive(brokerB, brokerC); - - brokerC.stop(); - brokerC.waitUntilStopped(); - } - - /** - * networked broker started after target so first connect attempt succeeds - * start order is important - */ - @Test - public void testSendReceive() throws Exception { - - brokerA = createBroker("tcp", "61617", null); - brokerA.start(); - brokerB = createBroker("tcp", "62617", new String[]{"61617", "1111"}); - brokerB.start(); - - doTestNetworkSendReceive(); - } - - @Test - public void testSendReceiveSsl() throws Exception { - - brokerA = createBroker("ssl", "61617", null); - brokerA.start(); - brokerB = createBroker("ssl", "62617", new String[]{"61617", "1111"}); - brokerB.start(); - - doTestNetworkSendReceive(); - } - - @Test - public void testRepeatedSendReceiveWithMasterSlaveAlternate() throws Exception { - doTestRepeatedSendReceiveWithMasterSlaveAlternate(null); - } - - @Test - public void testRepeatedSendReceiveWithMasterSlaveAlternateDuplex() throws Exception { - HashMap networkConnectorProps = new HashMap<>(); - networkConnectorProps.put("duplex", "true"); - - doTestRepeatedSendReceiveWithMasterSlaveAlternate(networkConnectorProps); - } - - public void doTestRepeatedSendReceiveWithMasterSlaveAlternate(HashMap networkConnectorProps) throws Exception { - - brokerB = createBroker("tcp", "62617", new String[]{"61610", "61611"}, networkConnectorProps); - brokerB.start(); - - final AtomicBoolean done = new AtomicBoolean(false); - ExecutorService executorService = Executors.newCachedThreadPool(); - executorService.execute(new Runnable() { - @Override - public void run() { - try { - while (!done.get()) { - brokerA = createBroker("tcp", "61610", null); - brokerA.setBrokerName("Pair"); - brokerA.setBrokerObjectName(new ObjectName(brokerA.getManagementContext().getJmxDomainName() + ":" + "BrokerName=" + JMXSupport.encodeObjectNamePart("A") + "," + "Type=Broker")); - ((KahaDBPersistenceAdapter) brokerA.getPersistenceAdapter()).getLocker().setLockAcquireSleepInterval(1000); - brokerA.start(); - brokerA.waitUntilStopped(); - - // restart after peer taken over - brokerA1.waitUntilStarted(); - } - } catch (Exception ignored) { - LOG.info("A create/start, unexpected: " + ignored, ignored); - } - } - }); - - // start with brokerA as master - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return brokerA != null && brokerA.waitUntilStarted(); - } - }); - - executorService.execute(new Runnable() { - @Override - public void run() { - try { - while (!done.get()) { - brokerA1 = createBroker("tcp", "61611", null); - brokerA1.setBrokerName("Pair"); - // so they can coexist in local jmx we set the object name b/c the brokername identifies the shared store - brokerA1.setBrokerObjectName(new ObjectName(brokerA.getManagementContext().getJmxDomainName() + ":" + "BrokerName=" + JMXSupport.encodeObjectNamePart("A1") + "," + "Type=Broker")); - ((KahaDBPersistenceAdapter) brokerA1.getPersistenceAdapter()).getLocker().setLockAcquireSleepInterval(1000); - brokerA1.start(); - brokerA1.waitUntilStopped(); - - // restart after peer taken over - brokerA.waitUntilStarted(); - } - } catch (Exception ignored) { - LOG.info("A1 create/start, unexpected: " + ignored, ignored); - } - } - }); - - for (int i = 0; i < 4; i++) { - BrokerService currentMaster = (i % 2 == 0 ? brokerA : brokerA1); - LOG.info("iteration: " + i + ", using: " + currentMaster.getBrokerObjectName().getKeyProperty("BrokerName")); - currentMaster.waitUntilStarted(); - - doTestNetworkSendReceive(brokerB, currentMaster); - - LOG.info("Stopping " + currentMaster.getBrokerObjectName().getKeyProperty("BrokerName")); - currentMaster.stop(); - currentMaster.waitUntilStopped(); - } - - done.set(true); - LOG.info("all done"); - executorService.shutdownNow(); - } - - private void doTestNetworkSendReceive() throws Exception, JMSException { - doTestNetworkSendReceive(brokerB, brokerA); - } - - private void doTestNetworkSendReceive(final BrokerService to, - final BrokerService from) throws Exception, JMSException { - - LOG.info("Creating Consumer on the networked broker ..." + from); - - SslContext.setCurrentSslContext(sslContext); - // Create a consumer on brokerA - ConnectionFactory consFactory = createConnectionFactory(from); - Connection consConn = consFactory.createConnection(); - consConn.start(); - Session consSession = consConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination = (ActiveMQDestination) consSession.createQueue(DESTINATION_NAME); - final MessageConsumer consumer = consSession.createConsumer(destination); - - LOG.info("publishing to " + to); - - sendMessageTo(destination, to); - - boolean gotMessage = Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = consumer.receive(5000); - LOG.info("from: " + from.getBrokerObjectName().getKeyProperty("BrokerName") + ", received: " + message); - return message != null; - } - }); - try { - consConn.close(); - } catch (JMSException ignored) { - } - assertTrue("consumer on A got message", gotMessage); - } - - private void sendMessageTo(ActiveMQDestination destination, BrokerService brokerService) throws Exception { - ConnectionFactory factory = createConnectionFactory(brokerService); - Connection conn = factory.createConnection(); - conn.start(); - Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createProducer(destination).send(session.createTextMessage("Hi")); - conn.close(); - } - - protected ConnectionFactory createConnectionFactory(final BrokerService broker) throws Exception { - String url = broker.getTransportConnectors().get(0).getServer().getConnectURI().toString(); - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url); - connectionFactory.setOptimizedMessageDispatch(true); - connectionFactory.setDispatchAsync(false); - connectionFactory.setUseAsyncSend(false); - connectionFactory.setOptimizeAcknowledge(false); - connectionFactory.setAlwaysSyncSend(true); - return connectionFactory; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/ForwardingBridgeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/ForwardingBridgeTest.java deleted file mode 100644 index d11c44b292..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/ForwardingBridgeTest.java +++ /dev/null @@ -1,152 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network; - -import javax.jms.DeliveryMode; - -import junit.framework.Test; - -import org.apache.activemq.broker.StubConnection; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQMessage; -import org.apache.activemq.command.ConnectionInfo; -import org.apache.activemq.command.ConsumerInfo; -import org.apache.activemq.command.Message; -import org.apache.activemq.command.ProducerInfo; -import org.apache.activemq.command.SessionInfo; - -public class ForwardingBridgeTest extends NetworkTestSupport { - - public ActiveMQDestination destination; - public byte destinationType; - public int deliveryMode; - private ForwardingBridge bridge; - - public void initCombosForTestForwardMessageCompressed() { - addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); - } - - public void testForwardMessageCompressed() throws Exception { - - bridge.setUseCompression(true); - - // Start a producer on local broker - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo); - - destination = createDestinationInfo(connection1, connectionInfo1, destinationType); - - // Start a consumer on a remote broker - StubConnection connection2 = createRemoteConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo2, destination); - connection2.send(consumerInfo); - Thread.sleep(1000); - // Give forwarding bridge a chance to finish setting up - try { - Thread.sleep(1000); - } catch (InterruptedException ie) { - ie.printStackTrace(); - } - - // Send the message to the local boker. - connection1.send(createMessage(producerInfo, destination, deliveryMode)); - - // Make sure the message was delivered via the remote. - Message m = receiveMessage(connection2); - assertNotNull(m); - - // Make sure its compressed now - ActiveMQMessage message = (ActiveMQMessage) m; - assertTrue(message.isCompressed()); - } - - public void initCombosForTestAddConsumerThenSend() { - addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); - } - - public void testAddConsumerThenSend() throws Exception { - // Start a producer on local broker - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo); - - destination = createDestinationInfo(connection1, connectionInfo1, destinationType); - - // Start a consumer on a remote broker - StubConnection connection2 = createRemoteConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo2, destination); - connection2.send(consumerInfo); - Thread.sleep(1000); - // Give forwarding bridge a chance to finish setting up - try { - Thread.sleep(1000); - } catch (InterruptedException ie) { - ie.printStackTrace(); - } - - // Send the message to the local boker. - connection1.send(createMessage(producerInfo, destination, deliveryMode)); - - // Make sure the message was delivered via the remote. - - Message m = receiveMessage(connection2); - assertNotNull(m); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - bridge = new ForwardingBridge(createTransport(), createRemoteTransport()); - bridge.setClientId("local-remote-bridge"); - bridge.setDispatchAsync(false); - bridge.start(); - } - - @Override - protected void tearDown() throws Exception { - bridge.stop(); - super.tearDown(); - } - - public static Test suite() { - return suite(ForwardingBridgeTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/MQTTNetworkOfBrokersFailoverTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/MQTTNetworkOfBrokersFailoverTest.java deleted file mode 100644 index 744dd381a2..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/MQTTNetworkOfBrokersFailoverTest.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.activemq.network; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.Session; -import javax.management.ObjectName; -import java.net.URI; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.broker.jmx.BrokerViewMBean; -import org.apache.activemq.broker.jmx.DurableSubscriptionViewMBean; -import org.apache.activemq.store.PersistenceAdapter; -import org.apache.commons.lang.ArrayUtils; -import org.fusesource.hawtdispatch.Dispatch; -import org.fusesource.mqtt.client.BlockingConnection; -import org.fusesource.mqtt.client.MQTT; -import org.fusesource.mqtt.client.QoS; -import org.fusesource.mqtt.client.Topic; -import org.fusesource.mqtt.client.Tracer; -import org.fusesource.mqtt.codec.MQTTFrame; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MQTTNetworkOfBrokersFailoverTest extends NetworkTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(MQTTNetworkOfBrokersFailoverTest.class); - private int localBrokerMQTTPort = -1; - private int remoteBrokerMQTTPort = -1; - - @Override - protected void setUp() throws Exception { - useJmx = true; - super.setUp(); - - URI ncUri = new URI("static:(" + connector.getConnectUri().toString() + ")"); - NetworkConnector nc = new DiscoveryNetworkConnector(ncUri); - nc.setDuplex(true); - remoteBroker.addNetworkConnector(nc); - nc.start(); - - // mqtt port should have been assigned by now - assertFalse(localBrokerMQTTPort == -1); - assertFalse(remoteBrokerMQTTPort == -1); - } - - @Override - protected void tearDown() throws Exception { - if (remoteBroker.isStarted()) { - remoteBroker.stop(); - remoteBroker.waitUntilStopped(); - } - if (broker.isStarted()) { - broker.stop(); - broker.waitUntilStopped(); - } - super.tearDown(); - } - - @Test - public void testNoStaleSubscriptionAcrossNetwork() throws Exception { - - // before we get started, we want an async way to be able to know when - // the durable consumer has been networked so we can assert that it indeed - // would have a durable subscriber. for example, when we subscribe on remote broker, - // a network-sub would be created on local broker and we want to listen for when that - // even happens. we do that with advisory messages and a latch: - CountDownLatch consumerNetworked = listenForConsumersOn(broker); - - // create a subscription with Clean == 0 (durable sub for QoS==1 && QoS==2) - // on the remote broker. this sub should still be there after we disconnect - MQTT remoteMqtt = createMQTTTcpConnection("foo", false, remoteBrokerMQTTPort); - BlockingConnection remoteConn = remoteMqtt.blockingConnection(); - remoteConn.connect(); - remoteConn.subscribe(new Topic[]{new Topic("foo/bar", QoS.AT_LEAST_ONCE)}); - - assertTrue("No destination detected!", consumerNetworked.await(1, TimeUnit.SECONDS)); - assertQueueExistsOn(remoteBroker, "Consumer.foo_AT_LEAST_ONCE.VirtualTopic.foo.bar"); - assertQueueExistsOn(broker, "Consumer.foo_AT_LEAST_ONCE.VirtualTopic.foo.bar"); - remoteConn.disconnect(); - - // now we reconnect the same sub on the local broker, again with clean==0 - MQTT localMqtt = createMQTTTcpConnection("foo", false, localBrokerMQTTPort); - BlockingConnection localConn = localMqtt.blockingConnection(); - localConn.connect(); - localConn.subscribe(new Topic[]{new Topic("foo/bar", QoS.AT_LEAST_ONCE)}); - - // now let's connect back up to remote broker and send a message - remoteConn = remoteMqtt.blockingConnection(); - remoteConn.connect(); - remoteConn.publish("foo/bar", "Hello, World!".getBytes(), QoS.AT_LEAST_ONCE, false); - - // now we should see that message on the local broker because the subscription - // should have been properly networked... we'll give a sec of grace for the - // networking and forwarding to have happened properly - org.fusesource.mqtt.client.Message msg = localConn.receive(100, TimeUnit.SECONDS); - assertNotNull(msg); - msg.ack(); - String response = new String(msg.getPayload()); - assertEquals("Hello, World!", response); - assertEquals("foo/bar", msg.getTopic()); - - // Now... we SHOULD NOT see a message on the remote broker because we already - // consumed it on the local broker... having the same message on the remote broker - // would effectively give us duplicates in a distributed topic scenario: - remoteConn.subscribe(new Topic[]{new Topic("foo/bar", QoS.AT_LEAST_ONCE)}); - msg = remoteConn.receive(500, TimeUnit.MILLISECONDS); - assertNull("We have duplicate messages across the cluster for a distributed topic", msg); - } - - private CountDownLatch listenForConsumersOn(BrokerService broker) throws Exception { - final CountDownLatch latch = new CountDownLatch(1); - - URI brokerUri = broker.getVmConnectorURI(); - - final ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(brokerUri.toASCIIString()); - final Connection connection = cf.createConnection(); - connection.start(); - final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination dest = session.createTopic("ActiveMQ.Advisory.Consumer.Queue.Consumer.foo:AT_LEAST_ONCE.VirtualTopic.foo.bar"); - MessageConsumer consumer = session.createConsumer(dest); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - latch.countDown(); - // shutdown this connection - Dispatch.getGlobalQueue().execute(new Runnable() { - @Override - public void run() { - try { - session.close(); - connection.close(); - } catch (JMSException e) { - e.printStackTrace(); - } - } - }); - } - }); - - return latch; - } - - private void assertQueueExistsOn(BrokerService broker, String queueName) throws Exception { - BrokerViewMBean brokerView = broker.getAdminView(); - ObjectName[] queueNames = brokerView.getQueues(); - assertEquals(1, queueNames.length); - - assertTrue(queueNames[0].toString().contains(queueName)); - } - - @SuppressWarnings("unused") - private void assertOneDurableSubOn(BrokerService broker, String subName) throws Exception { - BrokerViewMBean brokerView = broker.getAdminView(); - ObjectName[] activeDurableSubs = brokerView.getDurableTopicSubscribers(); - ObjectName[] inactiveDurableSubs = brokerView.getInactiveDurableTopicSubscribers(); - ObjectName[] allDurables = (ObjectName[]) ArrayUtils.addAll(activeDurableSubs, inactiveDurableSubs); - assertEquals(1, allDurables.length); - - // at this point our assertions should prove that we have only on durable sub - DurableSubscriptionViewMBean durableSubView = (DurableSubscriptionViewMBean) broker.getManagementContext().newProxyInstance(allDurables[0], DurableSubscriptionViewMBean.class, true); - - assertEquals(subName, durableSubView.getClientId()); - } - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - broker.setPersistent(true); - broker.setBrokerName("local"); - broker.setDataDirectory("target/activemq-data"); - broker.setDeleteAllMessagesOnStartup(true); - TransportConnector tc = broker.addConnector(getDefaultMQTTTransportConnectorUri()); - localBrokerMQTTPort = tc.getConnectUri().getPort(); - return broker; - } - - @Override - protected BrokerService createRemoteBroker(PersistenceAdapter persistenceAdapter) throws Exception { - BrokerService broker = super.createRemoteBroker(persistenceAdapter); - broker.setPersistent(true); - broker.setDeleteAllMessagesOnStartup(true); - broker.setDataDirectory("target/activemq-data"); - TransportConnector tc = broker.addConnector(getDefaultMQTTTransportConnectorUri()); - remoteBrokerMQTTPort = tc.getConnectUri().getPort(); - return broker; - } - - private String getDefaultMQTTTransportConnectorUri() { - return "mqtt://localhost:0?transport.subscriptionStrategy=mqtt-virtual-topic-subscriptions"; - } - - private MQTT createMQTTTcpConnection(String clientId, boolean clean, int port) throws Exception { - MQTT mqtt = new MQTT(); - mqtt.setConnectAttemptsMax(1); - mqtt.setReconnectAttemptsMax(0); - mqtt.setTracer(createTracer()); - if (clientId != null) { - mqtt.setClientId(clientId); - } - mqtt.setCleanSession(clean); - mqtt.setHost("localhost", port); - return mqtt; - } - - protected Tracer createTracer() { - return new Tracer() { - @Override - public void onReceive(MQTTFrame frame) { - LOG.info("Client Received:\n" + frame); - } - - @Override - public void onSend(MQTTFrame frame) { - LOG.info("Client Sent:\n" + frame); - } - - @Override - public void debug(String message, Object... args) { - LOG.info(String.format(message, args)); - } - }; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/MulticastNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/MulticastNetworkTest.java deleted file mode 100644 index c2b9cd9167..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/MulticastNetworkTest.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.activemq.network; - -/** - * - */ -public class MulticastNetworkTest extends SimpleNetworkTest { - - @Override - protected String getRemoteBrokerURI() { - return "org/apache/activemq/network/multicast/remoteBroker.xml"; - } - - @Override - protected String getLocalBrokerURI() { - return "org/apache/activemq/network/multicast/localBroker.xml"; - } - - // blocked out for multi cast because temp dest request reply isn't supported - // with dynamicallyAddedDestinations - @Override - public void testRequestReply() throws Exception { - - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkBrokerDetachTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkBrokerDetachTest.java deleted file mode 100644 index dfe16579c7..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkBrokerDetachTest.java +++ /dev/null @@ -1,300 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.Message; -import javax.jms.MessageListener; -import javax.jms.Session; -import javax.jms.TopicSubscriber; -import javax.management.ObjectName; -import java.io.File; -import java.util.Arrays; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ActiveMQPrefetchPolicy; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.jmx.BrokerView; -import org.apache.activemq.broker.jmx.DestinationViewMBean; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.util.Wait; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertTrue; - -public class NetworkBrokerDetachTest { - - private final static String BROKER_NAME = "broker"; - private final static String REM_BROKER_NAME = "networkedBroker"; - private final static String DESTINATION_NAME = "testQ"; - private final static int NUM_CONSUMERS = 1; - - protected static final Logger LOG = LoggerFactory.getLogger(NetworkBrokerDetachTest.class); - protected final int numRestarts = 3; - protected final int networkTTL = 2; - protected final boolean dynamicOnly = false; - - protected BrokerService broker; - protected BrokerService networkedBroker; - - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName(BROKER_NAME); - configureBroker(broker); - broker.addConnector("tcp://localhost:61617"); - NetworkConnector networkConnector = broker.addNetworkConnector("static:(tcp://localhost:62617?wireFormat.maxInactivityDuration=500)?useExponentialBackOff=false"); - configureNetworkConnector(networkConnector); - return broker; - } - - protected BrokerService createNetworkedBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName(REM_BROKER_NAME); - configureBroker(broker); - broker.getManagementContext().setCreateConnector(false); - broker.addConnector("tcp://localhost:62617"); - NetworkConnector networkConnector = broker.addNetworkConnector("static:(tcp://localhost:61617?wireFormat.maxInactivityDuration=500)?useExponentialBackOff=false"); - configureNetworkConnector(networkConnector); - return broker; - } - - private void configureNetworkConnector(NetworkConnector networkConnector) { - networkConnector.setDuplex(false); - networkConnector.setNetworkTTL(networkTTL); - networkConnector.setDynamicOnly(dynamicOnly); - } - - // variants for each store.... - protected void configureBroker(BrokerService broker) throws Exception { - KahaDBPersistenceAdapter persistenceAdapter = new KahaDBPersistenceAdapter(); - persistenceAdapter.setDirectory(new File("target/activemq-data/kahadb/" + broker.getBrokerName() + "NetworBrokerDetatchTest")); - broker.setPersistenceAdapter(persistenceAdapter); - } - - @Before - public void init() throws Exception { - broker = createBroker(); - broker.setDeleteAllMessagesOnStartup(true); - broker.start(); - - networkedBroker = createNetworkedBroker(); - networkedBroker.setDeleteAllMessagesOnStartup(true); - networkedBroker.start(); - } - - @After - public void cleanup() throws Exception { - networkedBroker.stop(); - networkedBroker.waitUntilStopped(); - - broker.stop(); - broker.waitUntilStopped(); - } - - @Test - public void testNetworkedBrokerDetach() throws Exception { - LOG.info("Creating Consumer on the networked broker ..."); - // Create a consumer on the networked broker - ConnectionFactory consFactory = createConnectionFactory(networkedBroker); - Connection consConn = consFactory.createConnection(); - Session consSession = consConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination = (ActiveMQDestination) consSession.createQueue(DESTINATION_NAME); - for (int i = 0; i < NUM_CONSUMERS; i++) { - consSession.createConsumer(destination); - } - - assertTrue("got expected consumer count from mbean within time limit", verifyConsumerCount(1, destination, broker)); - - LOG.info("Stopping Consumer on the networked broker ..."); - // Closing the connection will also close the consumer - consConn.close(); - - // We should have 0 consumer for the queue on the local broker - assertTrue("got expected 0 count from mbean within time limit", verifyConsumerCount(0, destination, broker)); - } - - @Test - public void testNetworkedBrokerDurableSubAfterRestart() throws Exception { - - final AtomicInteger count = new AtomicInteger(0); - MessageListener counter = new MessageListener() { - @Override - public void onMessage(Message message) { - count.incrementAndGet(); - } - }; - - LOG.info("Creating durable consumer on each broker ..."); - ActiveMQTopic destination = registerDurableConsumer(networkedBroker, counter); - registerDurableConsumer(broker, counter); - - assertTrue("got expected consumer count from local broker mbean within time limit", verifyConsumerCount(2, destination, broker)); - - assertTrue("got expected consumer count from network broker mbean within time limit", verifyConsumerCount(2, destination, networkedBroker)); - - sendMessageTo(destination, broker); - - assertTrue("Got one message on each", verifyMessageCount(2, count)); - - LOG.info("Stopping brokerTwo..."); - networkedBroker.stop(); - networkedBroker.waitUntilStopped(); - - LOG.info("restarting broker Two..."); - networkedBroker = createNetworkedBroker(); - networkedBroker.start(); - - LOG.info("Recreating durable Consumer on the broker after restart..."); - registerDurableConsumer(networkedBroker, counter); - - // give advisories a chance to percolate - TimeUnit.SECONDS.sleep(5); - - sendMessageTo(destination, broker); - - // expect similar after restart - assertTrue("got expected consumer count from local broker mbean within time limit", verifyConsumerCount(2, destination, broker)); - - // a durable sub is auto bridged on restart unless dynamicOnly=true - assertTrue("got expected consumer count from network broker mbean within time limit", verifyConsumerCount(2, destination, networkedBroker)); - - assertTrue("got no inactive subs on broker", verifyDurableConsumerCount(0, broker)); - assertTrue("got no inactive subs on other broker", verifyDurableConsumerCount(0, networkedBroker)); - - assertTrue("Got two more messages after restart", verifyMessageCount(4, count)); - TimeUnit.SECONDS.sleep(1); - assertTrue("still Got just two more messages", verifyMessageCount(4, count)); - } - - private boolean verifyMessageCount(final int i, final AtomicInteger count) throws Exception { - return Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return i == count.get(); - } - }); - } - - private ActiveMQTopic registerDurableConsumer(BrokerService brokerService, - MessageListener listener) throws Exception { - ConnectionFactory factory = createConnectionFactory(brokerService); - Connection connection = factory.createConnection(); - connection.setClientID("DurableOne"); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQTopic destination = (ActiveMQTopic) session.createTopic(DESTINATION_NAME); - // unique to a broker - TopicSubscriber sub = session.createDurableSubscriber(destination, "SubOne" + brokerService.getBrokerName()); - sub.setMessageListener(listener); - return destination; - } - - private void sendMessageTo(ActiveMQTopic destination, BrokerService brokerService) throws Exception { - ConnectionFactory factory = createConnectionFactory(brokerService); - Connection conn = factory.createConnection(); - conn.start(); - Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createProducer(destination).send(session.createTextMessage("Hi")); - conn.close(); - } - - protected ConnectionFactory createConnectionFactory(final BrokerService broker) throws Exception { - String url = broker.getTransportConnectors().get(0).getServer().getConnectURI().toString(); - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url); - connectionFactory.setOptimizedMessageDispatch(true); - connectionFactory.setCopyMessageOnSend(false); - connectionFactory.setUseCompression(false); - connectionFactory.setDispatchAsync(false); - connectionFactory.setUseAsyncSend(false); - connectionFactory.setOptimizeAcknowledge(false); - connectionFactory.setWatchTopicAdvisories(true); - ActiveMQPrefetchPolicy qPrefetchPolicy = new ActiveMQPrefetchPolicy(); - qPrefetchPolicy.setQueuePrefetch(100); - qPrefetchPolicy.setTopicPrefetch(1000); - connectionFactory.setPrefetchPolicy(qPrefetchPolicy); - connectionFactory.setAlwaysSyncSend(true); - return connectionFactory; - } - - // JMX Helper Methods - private boolean verifyConsumerCount(final long expectedCount, - final ActiveMQDestination destination, - final BrokerService broker) throws Exception { - return Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - boolean result = false; - try { - - ObjectName[] destinations; - - if (destination.isQueue()) { - destinations = broker.getAdminView().getQueues(); - } else { - destinations = broker.getAdminView().getTopics(); - } - - // We should have 1 consumer for the queue on the local broker - for (ObjectName name : destinations) { - DestinationViewMBean view = (DestinationViewMBean) broker.getManagementContext().newProxyInstance(name, DestinationViewMBean.class, true); - - if (view.getName().equals(destination.getPhysicalName())) { - LOG.info("Consumers for " + destination.getPhysicalName() + " on " + broker + " : " + view.getConsumerCount()); - LOG.info("Subs: " + Arrays.asList(view.getSubscriptions())); - if (expectedCount == view.getConsumerCount()) { - result = true; - } - } - } - - } catch (Exception ignoreAndRetry) { - } - return result; - } - }); - } - - private boolean verifyDurableConsumerCount(final long expectedCount, final BrokerService broker) throws Exception { - return Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - boolean result = false; - BrokerView view = broker.getAdminView(); - - if (view != null) { - ObjectName[] subs = broker.getAdminView().getInactiveDurableTopicSubscribers(); - if (subs != null) { - LOG.info("inactive durable subs on " + broker + " : " + Arrays.asList(subs)); - if (expectedCount == subs.length) { - result = true; - } - } - } - return result; - } - }); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkConnectionsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkConnectionsTest.java deleted file mode 100644 index bc9422b279..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkConnectionsTest.java +++ /dev/null @@ -1,251 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQQueue; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class NetworkConnectionsTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(NetworkConnectionsTest.class); - - private static final String LOCAL_BROKER_TRANSPORT_URI = "tcp://localhost:61616"; - private static final String REMOTE_BROKER_TRANSPORT_URI = "tcp://localhost:61617"; - private static final String DESTINATION_NAME = "TEST.RECONNECT"; - - private BrokerService localBroker; - private BrokerService remoteBroker; - - @Test - public void testIsStarted() throws Exception { - LOG.info("testIsStarted is starting..."); - - LOG.info("Adding network connector..."); - NetworkConnector nc = localBroker.addNetworkConnector("static:(" + REMOTE_BROKER_TRANSPORT_URI + ")"); - nc.setName("NC1"); - - LOG.info("Starting network connector..."); - nc.start(); - assertTrue(nc.isStarted()); - - LOG.info("Stopping network connector..."); - nc.stop(); - - while (nc.isStopping()) { - LOG.info("... still stopping ..."); - Thread.sleep(100); - } - - assertTrue(nc.isStopped()); - assertFalse(nc.isStarted()); - - LOG.info("Starting network connector..."); - nc.start(); - assertTrue(nc.isStarted()); - - LOG.info("Stopping network connector..."); - nc.stop(); - - while (nc.isStopping()) { - LOG.info("... still stopping ..."); - Thread.sleep(100); - } - - assertTrue(nc.isStopped()); - assertFalse(nc.isStarted()); - } - - @Test - public void testNetworkConnectionRestart() throws Exception { - LOG.info("testNetworkConnectionRestart is starting..."); - - LOG.info("Adding network connector..."); - NetworkConnector nc = localBroker.addNetworkConnector("static:(" + REMOTE_BROKER_TRANSPORT_URI + ")"); - nc.setName("NC1"); - nc.start(); - assertTrue(nc.isStarted()); - - LOG.info("Setting up Message Producer and Consumer"); - ActiveMQQueue destination = new ActiveMQQueue(DESTINATION_NAME); - - ActiveMQConnectionFactory localFactory = new ActiveMQConnectionFactory(LOCAL_BROKER_TRANSPORT_URI); - Connection localConnection = localFactory.createConnection(); - localConnection.start(); - Session localSession = localConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer localProducer = localSession.createProducer(destination); - - ActiveMQConnectionFactory remoteFactory = new ActiveMQConnectionFactory(REMOTE_BROKER_TRANSPORT_URI); - Connection remoteConnection = remoteFactory.createConnection(); - remoteConnection.start(); - Session remoteSession = remoteConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer remoteConsumer = remoteSession.createConsumer(destination); - - Message message = localSession.createTextMessage("test"); - localProducer.send(message); - - LOG.info("Testing initial network connection..."); - message = remoteConsumer.receive(10000); - assertNotNull(message); - - LOG.info("Stopping network connection..."); - nc.stop(); - assertFalse(nc.isStarted()); - - LOG.info("Sending 2nd message..."); - message = localSession.createTextMessage("test stop"); - localProducer.send(message); - - message = remoteConsumer.receive(1000); - assertNull("Message should not have been delivered since NetworkConnector was stopped", message); - - LOG.info("(Re)starting network connection..."); - nc.start(); - assertTrue(nc.isStarted()); - - LOG.info("Wait for 2nd message to get forwarded and received..."); - message = remoteConsumer.receive(10000); - assertNotNull("Should have received 2nd message", message); - } - - @Test - public void testNetworkConnectionReAddURI() throws Exception { - LOG.info("testNetworkConnectionReAddURI is starting..."); - - LOG.info("Adding network connector 'NC1'..."); - NetworkConnector nc = localBroker.addNetworkConnector("static:(" + REMOTE_BROKER_TRANSPORT_URI + ")"); - nc.setName("NC1"); - nc.start(); - assertTrue(nc.isStarted()); - - LOG.info("Looking up network connector by name..."); - NetworkConnector nc1 = localBroker.getNetworkConnectorByName("NC1"); - assertNotNull("Should find network connector 'NC1'", nc1); - assertTrue(nc1.isStarted()); - assertEquals(nc, nc1); - - LOG.info("Setting up producer and consumer..."); - ActiveMQQueue destination = new ActiveMQQueue(DESTINATION_NAME); - - ActiveMQConnectionFactory localFactory = new ActiveMQConnectionFactory(LOCAL_BROKER_TRANSPORT_URI); - Connection localConnection = localFactory.createConnection(); - localConnection.start(); - Session localSession = localConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer localProducer = localSession.createProducer(destination); - - ActiveMQConnectionFactory remoteFactory = new ActiveMQConnectionFactory(REMOTE_BROKER_TRANSPORT_URI); - Connection remoteConnection = remoteFactory.createConnection(); - remoteConnection.start(); - Session remoteSession = remoteConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer remoteConsumer = remoteSession.createConsumer(destination); - - Message message = localSession.createTextMessage("test"); - localProducer.send(message); - - LOG.info("Testing initial network connection..."); - message = remoteConsumer.receive(10000); - assertNotNull(message); - - LOG.info("Stopping network connector 'NC1'..."); - nc.stop(); - assertFalse(nc.isStarted()); - - LOG.info("Removing network connector..."); - assertTrue(localBroker.removeNetworkConnector(nc)); - - nc1 = localBroker.getNetworkConnectorByName("NC1"); - assertNull("Should not find network connector 'NC1'", nc1); - - LOG.info("Re-adding network connector 'NC2'..."); - nc = localBroker.addNetworkConnector("static:(" + REMOTE_BROKER_TRANSPORT_URI + ")"); - nc.setName("NC2"); - nc.start(); - assertTrue(nc.isStarted()); - - LOG.info("Looking up network connector by name..."); - NetworkConnector nc2 = localBroker.getNetworkConnectorByName("NC2"); - assertNotNull(nc2); - assertTrue(nc2.isStarted()); - assertEquals(nc, nc2); - - LOG.info("Testing re-added network connection..."); - message = localSession.createTextMessage("test"); - localProducer.send(message); - - message = remoteConsumer.receive(10000); - assertNotNull(message); - - LOG.info("Stopping network connector..."); - nc.stop(); - assertFalse(nc.isStarted()); - - LOG.info("Removing network connection 'NC2'"); - assertTrue(localBroker.removeNetworkConnector(nc)); - - nc2 = localBroker.getNetworkConnectorByName("NC2"); - assertNull("Should not find network connector 'NC2'", nc2); - } - - @Override - protected void setUp() throws Exception { - LOG.info("Setting up LocalBroker"); - localBroker = new BrokerService(); - localBroker.setBrokerName("LocalBroker"); - localBroker.setUseJmx(false); - localBroker.setPersistent(false); - localBroker.setTransportConnectorURIs(new String[]{LOCAL_BROKER_TRANSPORT_URI}); - localBroker.start(); - localBroker.waitUntilStarted(); - - LOG.info("Setting up RemoteBroker"); - remoteBroker = new BrokerService(); - remoteBroker.setBrokerName("RemoteBroker"); - remoteBroker.setUseJmx(false); - remoteBroker.setPersistent(false); - remoteBroker.setTransportConnectorURIs(new String[]{REMOTE_BROKER_TRANSPORT_URI}); - remoteBroker.start(); - remoteBroker.waitUntilStarted(); - } - - @Override - protected void tearDown() throws Exception { - if (localBroker.isStarted()) { - LOG.info("Stopping LocalBroker"); - localBroker.stop(); - localBroker.waitUntilStopped(); - localBroker = null; - } - - if (remoteBroker.isStarted()) { - LOG.info("Stopping RemoteBroker"); - remoteBroker.stop(); - remoteBroker.waitUntilStopped(); - remoteBroker = null; - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkDestinationFilterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkDestinationFilterTest.java deleted file mode 100644 index a16f9b0d91..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkDestinationFilterTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network; - -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.activemq.advisory.AdvisorySupport; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTempQueue; -import org.apache.activemq.command.ActiveMQTopic; - -public class NetworkDestinationFilterTest extends TestCase { - - public void testFilter() throws Exception { - NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); - assertEquals(AdvisorySupport.CONSUMER_ADVISORY_TOPIC_PREFIX + ">", config.getDestinationFilter()); - List dests = new ArrayList<>(); - config.setDynamicallyIncludedDestinations(dests); - assertEquals(AdvisorySupport.CONSUMER_ADVISORY_TOPIC_PREFIX + ">", config.getDestinationFilter()); - dests.add(new ActiveMQQueue("TEST.>")); - dests.add(new ActiveMQTopic("TEST.>")); - dests.add(new ActiveMQTempQueue("TEST.>")); - String prefix = AdvisorySupport.CONSUMER_ADVISORY_TOPIC_PREFIX; - assertEquals(prefix + "Queue.TEST.>," + prefix + "Topic.TEST.>", config.getDestinationFilter()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkFailoverTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkFailoverTest.java deleted file mode 100644 index 1475254068..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkFailoverTest.java +++ /dev/null @@ -1,225 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.io.IOException; -import java.util.concurrent.atomic.AtomicInteger; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.DestinationDoesNotExistException; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.SharedDeadLetterStrategy; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.transport.TransportFilter; -import org.apache.activemq.transport.failover.FailoverTransport; -import org.apache.activemq.xbean.BrokerFactoryBean; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.support.AbstractApplicationContext; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; - -public class NetworkFailoverTest extends TestCase { - - protected static final int MESSAGE_COUNT = 10; - private static final Logger LOG = LoggerFactory.getLogger(NetworkFailoverTest.class); - - protected AbstractApplicationContext context; - protected Connection localConnection; - protected Connection remoteConnection; - protected BrokerService localBroker; - protected BrokerService remoteBroker; - protected Session localSession; - protected Session remoteSession; - protected ActiveMQQueue included = new ActiveMQQueue("include.test.foo"); - private final AtomicInteger replyToNonExistDest = new AtomicInteger(0); - private final AtomicInteger roundTripComplete = new AtomicInteger(0); - private final AtomicInteger remoteDLQCount = new AtomicInteger(0); - - public void testRequestReply() throws Exception { - final MessageProducer remoteProducer = remoteSession.createProducer(null); - MessageConsumer remoteConsumer = remoteSession.createConsumer(included); - remoteConsumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message msg) { - final TextMessage textMsg = (TextMessage) msg; - try { - String payload = "REPLY: " + textMsg.getText() + ", " + textMsg.getJMSMessageID(); - Destination replyTo; - replyTo = msg.getJMSReplyTo(); - textMsg.clearBody(); - textMsg.setText(payload); - LOG.info("*** Sending response: {}", textMsg.getText()); - remoteProducer.send(replyTo, textMsg); - LOG.info("replied with: " + textMsg.getJMSMessageID()); - - } catch (DestinationDoesNotExistException expected) { - // been removed but not yet recreated - replyToNonExistDest.incrementAndGet(); - try { - LOG.info("NED: " + textMsg.getJMSMessageID()); - } catch (JMSException e) { - e.printStackTrace(); - } - } catch (Exception e) { - LOG.warn("*** Responder listener caught exception: ", e); - e.printStackTrace(); - } - } - }); - - Queue tempQueue = localSession.createTemporaryQueue(); - MessageProducer requestProducer = localSession.createProducer(included); - requestProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - MessageConsumer requestConsumer = localSession.createConsumer(tempQueue); - - // track remote dlq for forward failures - MessageConsumer dlqconsumer = remoteSession.createConsumer(new ActiveMQQueue(SharedDeadLetterStrategy.DEFAULT_DEAD_LETTER_QUEUE_NAME)); - dlqconsumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - try { - LOG.info("dlq " + message.getJMSMessageID()); - } catch (JMSException e) { - e.printStackTrace(); - } - remoteDLQCount.incrementAndGet(); - } - }); - - // allow for consumer infos to perculate around - Thread.sleep(2000); - long done = System.currentTimeMillis() + (MESSAGE_COUNT * 6000); - int i = 0; - while (MESSAGE_COUNT > roundTripComplete.get() + remoteDLQCount.get() + replyToNonExistDest.get() && done > System.currentTimeMillis()) { - if (i < MESSAGE_COUNT) { - String payload = "test msg " + i; - i++; - TextMessage msg = localSession.createTextMessage(payload); - msg.setJMSReplyTo(tempQueue); - requestProducer.send(msg); - LOG.info("Sent: " + msg.getJMSMessageID() + ", Failing over"); - ((FailoverTransport) ((TransportFilter) ((TransportFilter) ((ActiveMQConnection) localConnection).getTransport()).getNext()).getNext()).handleTransportFailure(new IOException("Forcing failover from test")); - } - TextMessage result = (TextMessage) requestConsumer.receive(5000); - if (result != null) { - LOG.info("Got reply: " + result.getJMSMessageID() + ", " + result.getText()); - roundTripComplete.incrementAndGet(); - } - } - - LOG.info("complete: " + roundTripComplete.get() + ", remoteDLQCount: " + remoteDLQCount.get() + ", replyToNonExistDest: " + replyToNonExistDest.get()); - assertEquals("complete:" + roundTripComplete.get() + ", remoteDLQCount: " + remoteDLQCount.get() + ", replyToNonExistDest: " + replyToNonExistDest.get(), MESSAGE_COUNT, roundTripComplete.get() + remoteDLQCount.get() + replyToNonExistDest.get()); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - doSetUp(true); - } - - @Override - protected void tearDown() throws Exception { - doTearDown(); - super.tearDown(); - } - - protected void doTearDown() throws Exception { - try { - localConnection.close(); - remoteConnection.close(); - } catch (Exception ex) { - } - - try { - localBroker.stop(); - } catch (Exception ex) { - } - try { - remoteBroker.stop(); - } catch (Exception ex) { - } - } - - protected void doSetUp(boolean deleteAllMessages) throws Exception { - - remoteBroker = createRemoteBroker(); - remoteBroker.setDeleteAllMessagesOnStartup(deleteAllMessages); - remoteBroker.setCacheTempDestinations(true); - remoteBroker.start(); - - localBroker = createLocalBroker(); - localBroker.setDeleteAllMessagesOnStartup(deleteAllMessages); - localBroker.setCacheTempDestinations(true); - localBroker.start(); - - String localURI = "tcp://localhost:61616"; - String remoteURI = "tcp://localhost:61617"; - ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory("failover:(" + localURI + "," + remoteURI + ")?randomize=false&backup=false&trackMessages=true"); - localConnection = fac.createConnection(); - localConnection.setClientID("local"); - localConnection.start(); - fac = new ActiveMQConnectionFactory("failover:(" + remoteURI + "," + localURI + ")?randomize=false&backup=false&trackMessages=true"); - fac.setWatchTopicAdvisories(false); - remoteConnection = fac.createConnection(); - remoteConnection.setClientID("remote"); - remoteConnection.start(); - - localSession = localConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - remoteSession = remoteConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } - - protected String getRemoteBrokerURI() { - return "org/apache/activemq/network/remoteBroker.xml"; - } - - protected String getLocalBrokerURI() { - return "org/apache/activemq/network/localBroker.xml"; - } - - protected BrokerService createBroker(String uri) throws Exception { - Resource resource = new ClassPathResource(uri); - BrokerFactoryBean factory = new BrokerFactoryBean(resource); - resource = new ClassPathResource(uri); - factory = new BrokerFactoryBean(resource); - factory.afterPropertiesSet(); - BrokerService result = factory.getBroker(); - return result; - } - - protected BrokerService createLocalBroker() throws Exception { - return createBroker(getLocalBrokerURI()); - } - - protected BrokerService createRemoteBroker() throws Exception { - return createBroker(getRemoteBrokerURI()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkLoadTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkLoadTest.java deleted file mode 100644 index fbf261c1ff..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkLoadTest.java +++ /dev/null @@ -1,336 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.net.URI; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ActiveMQPrefetchPolicy; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.broker.region.policy.NoSubscriptionRecoveryPolicy; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.broker.region.policy.VMPendingQueueMessageStoragePolicy; -import org.apache.activemq.broker.region.policy.VMPendingSubscriberMessageStoragePolicy; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTextMessage; -import org.apache.activemq.usage.SystemUsage; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This test case is used to load test store and forwarding between brokers. It sets up - * n brokers to which have a chain of queues which this test consumes and produces to. - * - * If the network bridges gets stuck at any point subsequent queues will not get messages. This test - * samples the production and consumption stats every second and if the flow of messages - * get stuck then this test fails. The test monitors the flow of messages for 1 min. - * - * @author chirino - */ -public class NetworkLoadTest extends TestCase { - - private static final transient Logger LOG = LoggerFactory.getLogger(NetworkLoadTest.class); - - // How many times do we sample? - private static final long SAMPLES = Integer.parseInt(System.getProperty("SAMPLES", "" + 60 * 1 / 5)); - // Slower machines might need to make this bigger. - private static final long SAMPLE_DURATION = Integer.parseInt(System.getProperty("SAMPLES_DURATION", "" + 1000 * 5)); - protected static final int BROKER_COUNT = 4; - protected static final int MESSAGE_SIZE = 2000; - String groupId; - - class ForwardingClient { - - private final AtomicLong forwardCounter = new AtomicLong(); - private final Connection toConnection; - private final Connection fromConnection; - - public ForwardingClient(int from, int to) throws JMSException { - toConnection = createConnection(from); - Session toSession = toConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageProducer producer = toSession.createProducer(new ActiveMQQueue("Q" + to)); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - producer.setDisableMessageID(true); - - fromConnection = createConnection(from); - Session fromSession = fromConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = fromSession.createConsumer(new ActiveMQQueue("Q" + from)); - - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message msg) { - try { - producer.send(msg); - forwardCounter.incrementAndGet(); - } catch (JMSException e) { - // this is caused by the connection getting closed. - } - } - }); - } - - public void start() throws JMSException { - toConnection.start(); - fromConnection.start(); - } - - public void stop() throws JMSException { - toConnection.stop(); - fromConnection.stop(); - } - - public void close() throws JMSException { - toConnection.close(); - fromConnection.close(); - } - } - - private BrokerService[] brokers; - private ForwardingClient[] forwardingClients; - - @Override - protected void setUp() throws Exception { - groupId = "network-load-test-" + System.currentTimeMillis(); - brokers = new BrokerService[BROKER_COUNT]; - for (int i = 0; i < brokers.length; i++) { - LOG.info("Starting broker: " + i); - brokers[i] = createBroker(i); - brokers[i].start(); - } - - // Wait for the network connection to get setup. - // The wait is exponential since every broker has to connect to every other broker. - Thread.sleep(BROKER_COUNT * BROKER_COUNT * 50); - - forwardingClients = new ForwardingClient[BROKER_COUNT - 1]; - for (int i = 0; i < forwardingClients.length; i++) { - LOG.info("Starting forwarding client " + i); - forwardingClients[i] = new ForwardingClient(i, i + 1); - forwardingClients[i].start(); - } - } - - @Override - protected void tearDown() throws Exception { - for (int i = 0; i < forwardingClients.length; i++) { - LOG.info("Stopping forwarding client " + i); - forwardingClients[i].close(); - } - for (int i = 0; i < brokers.length; i++) { - LOG.info("Stopping broker " + i); - brokers[i].stop(); - } - } - - protected Connection createConnection(int brokerId) throws JMSException { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:" + (60000 + brokerId)); - connectionFactory.setOptimizedMessageDispatch(true); - connectionFactory.setCopyMessageOnSend(false); - connectionFactory.setUseCompression(false); - connectionFactory.setDispatchAsync(true); - connectionFactory.setUseAsyncSend(false); - connectionFactory.setOptimizeAcknowledge(false); - connectionFactory.setWatchTopicAdvisories(false); - ActiveMQPrefetchPolicy qPrefetchPolicy = new ActiveMQPrefetchPolicy(); - qPrefetchPolicy.setQueuePrefetch(100); - qPrefetchPolicy.setTopicPrefetch(1000); - connectionFactory.setPrefetchPolicy(qPrefetchPolicy); - connectionFactory.setAlwaysSyncSend(true); - return connectionFactory.createConnection(); - } - - protected BrokerService createBroker(int brokerId) throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("broker-" + brokerId); - broker.setPersistent(false); - broker.setUseJmx(true); - broker.getManagementContext().setCreateConnector(false); - - final SystemUsage memoryManager = new SystemUsage(); - memoryManager.getMemoryUsage().setLimit(1024 * 1024 * 50); // 50 MB - broker.setSystemUsage(memoryManager); - - final List policyEntries = new ArrayList<>(); - final PolicyEntry entry = new PolicyEntry(); - entry.setQueue(">"); - entry.setMemoryLimit(1024 * 1024 * 1); // Set to 1 MB - entry.setPendingSubscriberPolicy(new VMPendingSubscriberMessageStoragePolicy()); - entry.setPendingQueuePolicy(new VMPendingQueueMessageStoragePolicy()); - policyEntries.add(entry); - - // This is to turn of the default behavior of storing topic messages for retroactive consumption - final PolicyEntry topicPolicyEntry = new PolicyEntry(); - topicPolicyEntry.setTopic(">"); - final NoSubscriptionRecoveryPolicy noSubscriptionRecoveryPolicy = new NoSubscriptionRecoveryPolicy(); - topicPolicyEntry.setSubscriptionRecoveryPolicy(noSubscriptionRecoveryPolicy); - - final PolicyMap policyMap = new PolicyMap(); - policyMap.setPolicyEntries(policyEntries); - broker.setDestinationPolicy(policyMap); - - TransportConnector transportConnector = new TransportConnector(); - transportConnector.setUri(new URI("tcp://localhost:" + (60000 + brokerId))); - - transportConnector.setDiscoveryUri(new URI("multicast://default?group=" + groupId)); - broker.addConnector(transportConnector); - - DiscoveryNetworkConnector networkConnector = new DiscoveryNetworkConnector(); - networkConnector.setUri(new URI("multicast://default?group=" + groupId)); - networkConnector.setBridgeTempDestinations(true); - networkConnector.setPrefetchSize(1); - broker.addNetworkConnector(networkConnector); - - return broker; - } - - public void testRequestReply() throws Exception { - - final int to = 0; // Send to the first broker - int from = brokers.length - 1; // consume from the last broker.. - - LOG.info("Staring Final Consumer"); - - Connection fromConnection = createConnection(from); - fromConnection.start(); - Session fromSession = fromConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = fromSession.createConsumer(new ActiveMQQueue("Q" + from)); - - final AtomicReference lastMessageReceived = new AtomicReference<>(); - final AtomicLong producedMessages = new AtomicLong(); - final AtomicLong receivedMessages = new AtomicLong(); - final AtomicBoolean done = new AtomicBoolean(); - - // Setup the consumer.. - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message msg) { - ActiveMQTextMessage m = (ActiveMQTextMessage) msg; - ActiveMQTextMessage last = lastMessageReceived.get(); - if (last != null) { - // Some order checking... - if (last.getMessageId().getProducerSequenceId() > m.getMessageId().getProducerSequenceId()) { - System.out.println("Received an out of order message. Got " + m.getMessageId() + ", expected something after " + last.getMessageId()); - } - } - lastMessageReceived.set(m); - receivedMessages.incrementAndGet(); - } - }); - - LOG.info("Staring Initial Producer"); - final Connection toConnection = createConnection(to); - Thread producer = new Thread("Producer") { - @Override - public void run() { - try { - toConnection.start(); - Session toSession = toConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageProducer producer = toSession.createProducer(new ActiveMQQueue("Q" + to)); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - producer.setDisableMessageID(true); - - for (int i = 0; !done.get(); i++) { - TextMessage msg = toSession.createTextMessage(createMessageText(i)); - producer.send(msg); - producedMessages.incrementAndGet(); - } - } catch (JMSException e) { - e.printStackTrace(); - } - } - - private String createMessageText(int index) { - StringBuffer buffer = new StringBuffer(MESSAGE_SIZE); - buffer.append(index + " on " + new Date() + " ..."); - if (buffer.length() > MESSAGE_SIZE) { - return buffer.substring(0, MESSAGE_SIZE); - } - for (int i = buffer.length(); i < MESSAGE_SIZE; i++) { - buffer.append(' '); - } - - return buffer.toString(); - } - }; - producer.start(); - - // Give the forwarding clients a chance to get going and fill the down - // stream broker queues.. - Thread.sleep(BROKER_COUNT * 200); - - for (int i = 0; i < SAMPLES; i++) { - - long start = System.currentTimeMillis(); - producedMessages.set(0); - receivedMessages.set(0); - for (int j = 0; j < forwardingClients.length; j++) { - forwardingClients[j].forwardCounter.set(0); - } - - Thread.sleep(SAMPLE_DURATION); - - long end = System.currentTimeMillis(); - long r = receivedMessages.get(); - long p = producedMessages.get(); - - LOG.info("published: " + p + " msgs at " + (p * 1000f / (end - start)) + " msgs/sec, " + "consumed: " + r + " msgs at " + (r * 1000f / (end - start)) + " msgs/sec"); - - StringBuffer fwdingmsg = new StringBuffer(500); - fwdingmsg.append(" forwarding counters: "); - for (int j = 0; j < forwardingClients.length; j++) { - if (j != 0) { - fwdingmsg.append(", "); - } - fwdingmsg.append(forwardingClients[j].forwardCounter.get()); - } - LOG.info(fwdingmsg.toString()); - - // The test is just checking to make sure thaat the producer and consumer does not hang - // due to the network hops take to route the message form the producer to the consumer. - assertTrue("Received some messages since last sample", r > 0); - assertTrue("Produced some messages since last sample", p > 0); - - } - LOG.info("Sample done."); - done.set(true); - // Wait for the producer to finish. - producer.join(1000 * 5); - toConnection.close(); - fromConnection.close(); - - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkLoopBackTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkLoopBackTest.java deleted file mode 100644 index a9ffceeebc..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkLoopBackTest.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.activemq.network; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.util.Wait; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class NetworkLoopBackTest { - - @Test - public void testLoopbackOnDifferentUrlScheme() throws Exception { - final BrokerService brokerServce = new BrokerService(); - brokerServce.setPersistent(false); - - TransportConnector transportConnector = brokerServce.addConnector("nio://0.0.0.0:0"); - // connection filter is bypassed when scheme is different - final NetworkConnector networkConnector = brokerServce.addNetworkConnector("static:(tcp://" + transportConnector.getConnectUri().getHost() + ":" + transportConnector.getConnectUri().getPort() + ")"); - - brokerServce.start(); - brokerServce.waitUntilStarted(); - - try { - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 1 == networkConnector.bridges.size(); - } - }); - - final DemandForwardingBridgeSupport loopbackBridge = (DemandForwardingBridgeSupport) networkConnector.bridges.values().iterator().next(); - assertTrue("nc started", networkConnector.isStarted()); - - assertTrue("It should get disposed", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return loopbackBridge.getRemoteBroker().isDisposed(); - } - })); - - assertEquals("No peer brokers", 0, brokerServce.getBroker().getPeerBrokerInfos().length); - - } finally { - brokerServce.stop(); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkReconnectTest.java deleted file mode 100644 index 0639fb1b80..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkReconnectTest.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.activemq.network; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.net.URI; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.concurrent.atomic.AtomicInteger; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.advisory.ConsumerEvent; -import org.apache.activemq.advisory.ConsumerEventSource; -import org.apache.activemq.advisory.ConsumerListener; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQQueue; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * These test cases are used to verifiy that network connections get re - * established in all broker restart scenarios. - * - * @author chirino - */ -public class NetworkReconnectTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(NetworkReconnectTest.class); - - private BrokerService producerBroker; - private BrokerService consumerBroker; - private ActiveMQConnectionFactory producerConnectionFactory; - private ActiveMQConnectionFactory consumerConnectionFactory; - private Destination destination; - private ArrayList connections = new ArrayList<>(); - - public void xtestMultipleProducerBrokerRestarts() throws Exception { - for (int i = 0; i < 10; i++) { - testWithProducerBrokerRestart(); - disposeConsumerConnections(); - } - } - - public void xtestWithoutRestarts() throws Exception { - startProducerBroker(); - startConsumerBroker(); - - MessageConsumer consumer = createConsumer(); - AtomicInteger counter = createConsumerCounter(producerConnectionFactory); - waitForConsumerToArrive(counter); - - String messageId = sendMessage(); - Message message = consumer.receive(1000); - - assertEquals(messageId, message.getJMSMessageID()); - - assertNull(consumer.receiveNoWait()); - - } - - public void testWithProducerBrokerRestart() throws Exception { - startProducerBroker(); - startConsumerBroker(); - - MessageConsumer consumer = createConsumer(); - AtomicInteger counter = createConsumerCounter(producerConnectionFactory); - waitForConsumerToArrive(counter); - - String messageId = sendMessage(); - Message message = consumer.receive(1000); - - assertEquals(messageId, message.getJMSMessageID()); - assertNull(consumer.receiveNoWait()); - - // Restart the first broker... - stopProducerBroker(); - startProducerBroker(); - - counter = createConsumerCounter(producerConnectionFactory); - waitForConsumerToArrive(counter); - - messageId = sendMessage(); - message = consumer.receive(1000); - - assertEquals(messageId, message.getJMSMessageID()); - assertNull(consumer.receiveNoWait()); - - } - - public void xtestWithConsumerBrokerRestart() throws Exception { - - startProducerBroker(); - startConsumerBroker(); - - MessageConsumer consumer = createConsumer(); - AtomicInteger counter = createConsumerCounter(producerConnectionFactory); - waitForConsumerToArrive(counter); - - String messageId = sendMessage(); - Message message = consumer.receive(1000); - - assertEquals(messageId, message.getJMSMessageID()); - assertNull(consumer.receiveNoWait()); - - // Restart the first broker... - stopConsumerBroker(); - waitForConsumerToLeave(counter); - startConsumerBroker(); - - consumer = createConsumer(); - waitForConsumerToArrive(counter); - - messageId = sendMessage(); - message = consumer.receive(1000); - - assertEquals(messageId, message.getJMSMessageID()); - assertNull(consumer.receiveNoWait()); - - } - - public void xtestWithConsumerBrokerStartDelay() throws Exception { - - startConsumerBroker(); - MessageConsumer consumer = createConsumer(); - - Thread.sleep(1000 * 5); - - startProducerBroker(); - AtomicInteger counter = createConsumerCounter(producerConnectionFactory); - waitForConsumerToArrive(counter); - - String messageId = sendMessage(); - Message message = consumer.receive(1000); - - assertEquals(messageId, message.getJMSMessageID()); - - assertNull(consumer.receiveNoWait()); - - } - - public void xtestWithProducerBrokerStartDelay() throws Exception { - - startProducerBroker(); - AtomicInteger counter = createConsumerCounter(producerConnectionFactory); - - Thread.sleep(1000 * 5); - - startConsumerBroker(); - MessageConsumer consumer = createConsumer(); - - waitForConsumerToArrive(counter); - - String messageId = sendMessage(); - Message message = consumer.receive(1000); - - assertEquals(messageId, message.getJMSMessageID()); - - assertNull(consumer.receiveNoWait()); - - } - - @Override - protected void setUp() throws Exception { - - LOG.info("==============================================================================="); - LOG.info("Running Test Case: " + getName()); - LOG.info("==============================================================================="); - - producerConnectionFactory = createProducerConnectionFactory(); - consumerConnectionFactory = createConsumerConnectionFactory(); - destination = new ActiveMQQueue("RECONNECT.TEST.QUEUE"); - - } - - @Override - protected void tearDown() throws Exception { - disposeConsumerConnections(); - try { - stopProducerBroker(); - } catch (Throwable e) { - } - try { - stopConsumerBroker(); - } catch (Throwable e) { - } - } - - protected void disposeConsumerConnections() { - for (Iterator iter = connections.iterator(); iter.hasNext(); ) { - Connection connection = iter.next(); - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } - - protected void startProducerBroker() throws Exception { - if (producerBroker == null) { - producerBroker = createFirstBroker(); - producerBroker.start(); - } - } - - protected void stopProducerBroker() throws Exception { - if (producerBroker != null) { - producerBroker.stop(); - producerBroker = null; - } - } - - protected void startConsumerBroker() throws Exception { - if (consumerBroker == null) { - consumerBroker = createSecondBroker(); - consumerBroker.start(); - } - } - - protected void stopConsumerBroker() throws Exception { - if (consumerBroker != null) { - consumerBroker.stop(); - consumerBroker = null; - } - } - - protected BrokerService createFirstBroker() throws Exception { - return BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/network/reconnect-broker1.xml")); - } - - protected BrokerService createSecondBroker() throws Exception { - return BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/network/reconnect-broker2.xml")); - } - - protected ActiveMQConnectionFactory createProducerConnectionFactory() { - return new ActiveMQConnectionFactory("vm://broker1"); - } - - protected ActiveMQConnectionFactory createConsumerConnectionFactory() { - return new ActiveMQConnectionFactory("vm://broker2"); - } - - protected String sendMessage() throws JMSException { - Connection connection = null; - try { - connection = producerConnectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - Message message = session.createMessage(); - producer.send(message); - return message.getJMSMessageID(); - } finally { - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } - - protected MessageConsumer createConsumer() throws JMSException { - Connection connection = consumerConnectionFactory.createConnection(); - connections.add(connection); - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - return session.createConsumer(destination); - } - - protected AtomicInteger createConsumerCounter(ActiveMQConnectionFactory cf) throws Exception { - final AtomicInteger rc = new AtomicInteger(0); - Connection connection = cf.createConnection(); - connections.add(connection); - connection.start(); - - ConsumerEventSource source = new ConsumerEventSource(connection, destination); - source.setConsumerListener(new ConsumerListener() { - @Override - public void onConsumerEvent(ConsumerEvent event) { - rc.set(event.getConsumerCount()); - } - }); - source.start(); - - return rc; - } - - protected void waitForConsumerToArrive(AtomicInteger consumerCounter) throws InterruptedException { - for (int i = 0; i < 100; i++) { - if (consumerCounter.get() > 0) { - return; - } - Thread.sleep(100); - } - fail("The consumer did not arrive."); - } - - protected void waitForConsumerToLeave(AtomicInteger consumerCounter) throws InterruptedException { - for (int i = 0; i < 100; i++) { - if (consumerCounter.get() == 0) { - return; - } - Thread.sleep(100); - } - fail("The consumer did not leave."); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRemovesSubscriptionsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRemovesSubscriptionsTest.java deleted file mode 100644 index f95db967f6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRemovesSubscriptionsTest.java +++ /dev/null @@ -1,191 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network; - -import javax.jms.Message; -import javax.jms.MessageListener; -import javax.jms.Session; -import javax.jms.TopicConnection; -import javax.jms.TopicSession; -import javax.jms.TopicSubscriber; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.Destination; -import org.apache.activemq.command.ActiveMQTopic; - -/** - * Various Tests to show the memory leak suspect in network of brokers. This is - * for https://issues.apache.org/activemq/browse/AMQ-2530 - */ -public class NetworkRemovesSubscriptionsTest extends TestCase { - - private final static String frontEndAddress = "tcp://0.0.0.0:61617"; - private final static String backEndAddress = "tcp://0.0.0.0:61616"; - private final static String TOPIC_NAME = "TEST_TOPIC"; - private BrokerService frontEnd; - private BrokerService backEnd; - private final ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(frontEndAddress); - private final ActiveMQTopic topic = new ActiveMQTopic(TOPIC_NAME); - - public void testWithSessionAndSubsciberClose() throws Exception { - - TopicConnection connection = connectionFactory.createTopicConnection(); - connection.start(); - - for (int i = 0; i < 100; i++) { - TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber subscriber = subscriberSession.createSubscriber(topic); - DummyMessageListener listener = new DummyMessageListener(); - subscriber.setMessageListener(listener); - subscriber.close(); - subscriberSession.close(); - } - connection.close(); - Thread.sleep(1000); - Destination dest = backEnd.getRegionBroker().getDestinationMap().get(topic); - assertNotNull(dest); - assertTrue(dest.getConsumers().isEmpty()); - } - - public void testWithSessionCloseOutsideTheLoop() throws Exception { - - TopicConnection connection = connectionFactory.createTopicConnection(); - connection.start(); - TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - for (int i = 0; i < 100; i++) { - - TopicSubscriber subscriber = subscriberSession.createSubscriber(topic); - DummyMessageListener listener = new DummyMessageListener(); - subscriber.setMessageListener(listener); - subscriber.close(); - } - subscriberSession.close(); - connection.close(); - Thread.sleep(1000); - Destination dest = backEnd.getRegionBroker().getDestinationMap().get(topic); - assertNotNull(dest); - assertTrue(dest.getConsumers().isEmpty()); - - } - - public void testWithOneSubscriber() throws Exception { - - TopicConnection connection = connectionFactory.createTopicConnection(); - connection.start(); - TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - - TopicSubscriber subscriber = subscriberSession.createSubscriber(topic); - DummyMessageListener listener = new DummyMessageListener(); - subscriber.setMessageListener(listener); - subscriber.close(); - subscriberSession.close(); - connection.close(); - Thread.sleep(1000); - Destination dest = backEnd.getRegionBroker().getDestinationMap().get(topic); - assertNotNull(dest); - assertTrue(dest.getConsumers().isEmpty()); - } - - public void testWithoutSessionAndSubsciberClose() throws Exception { - - TopicConnection connection = connectionFactory.createTopicConnection(); - connection.start(); - - for (int i = 0; i < 100; i++) { - TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber subscriber = subscriberSession.createSubscriber(topic); - assertNotNull(subscriber); - } - - connection.close(); - Thread.sleep(1000); - Destination dest = backEnd.getRegionBroker().getDestinationMap().get(topic); - assertNotNull(dest); - assertTrue(dest.getConsumers().isEmpty()); - } - - /** - * Running this test you can produce a leak of only 2 ConsumerInfo on BE - * broker, NOT 200 as in other cases! - */ - public void testWithoutSessionAndSubsciberClosePlayAround() throws Exception { - - TopicConnection connection = connectionFactory.createTopicConnection(); - connection.start(); - - for (int i = 0; i < 100; i++) { - TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber subscriber = subscriberSession.createSubscriber(topic); - DummyMessageListener listener = new DummyMessageListener(); - subscriber.setMessageListener(listener); - if (i != 50) { - subscriber.close(); - subscriberSession.close(); - } - } - - connection.close(); - Thread.sleep(1000); - Destination dest = backEnd.getRegionBroker().getDestinationMap().get(topic); - assertNotNull(dest); - assertTrue(dest.getConsumers().isEmpty()); - } - - class DummyMessageListener implements MessageListener { - - @Override - public void onMessage(Message arg0) { - // TODO Auto-generated method stub - - } - } - - @Override - protected void setUp() throws Exception { - this.backEnd = new BrokerService(); - this.backEnd.setBrokerName("backEnd"); - this.backEnd.setPersistent(false); - NetworkConnector backEndNetwork = this.backEnd.addNetworkConnector("static://" + frontEndAddress); - backEndNetwork.setName("backEndNetwork"); - backEndNetwork.setDynamicOnly(true); - this.backEnd.addConnector(backEndAddress); - this.backEnd.start(); - - this.frontEnd = new BrokerService(); - this.frontEnd.setBrokerName("frontEnd"); - this.frontEnd.setPersistent(false); - NetworkConnector frontEndNetwork = this.frontEnd.addNetworkConnector("static://" + backEndAddress); - frontEndNetwork.setName("frontEndNetwork"); - this.frontEnd.addConnector(frontEndAddress); - this.frontEnd.start(); - Thread.sleep(2000); - } - - @Override - protected void tearDown() throws Exception { - if (this.backEnd != null) { - this.backEnd.stop(); - } - if (this.frontEnd != null) { - this.frontEnd.stop(); - } - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRestartPlainTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRestartPlainTest.java deleted file mode 100644 index 30eda2de23..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRestartPlainTest.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network; - -public class NetworkRestartPlainTest extends NetworkRestartTest { - - @Override - protected String getLocalBrokerURI() { - return "org/apache/activemq/network/localBroker-plain.xml"; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRestartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRestartTest.java deleted file mode 100644 index eb09903d19..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRestartTest.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.activemq.network; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.TestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.xbean.BrokerFactoryBean; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; - -public class NetworkRestartTest extends TestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(NetworkRestartTest.class); - - protected Connection localConnection; - protected Connection remoteConnection; - protected BrokerService localBroker; - protected BrokerService remoteBroker; - protected Session localSession; - protected Session remoteSession; - - protected ActiveMQQueue included = new ActiveMQQueue("include.test.foo"); - - public void testConnectorRestart() throws Exception { - MessageConsumer remoteConsumer = remoteSession.createConsumer(included); - MessageProducer localProducer = localSession.createProducer(included); - - localProducer.send(localSession.createTextMessage("before")); - Message before = remoteConsumer.receive(1000); - assertNotNull(before); - assertEquals("before", ((TextMessage) before).getText()); - - // restart connector - - // wait for ack back to localbroker with concurrent store and dispatch, dispatch occurs first - Thread.sleep(1000); - - NetworkConnector connector = localBroker.getNetworkConnectorByName("networkConnector"); - - LOG.info("Stopping connector"); - connector.stop(); - - Thread.sleep(5000); - LOG.info("Starting connector"); - connector.start(); - - Thread.sleep(5000); - - localProducer.send(localSession.createTextMessage("after")); - Message after = remoteConsumer.receive(3000); - assertNotNull(after); - assertEquals("after", ((TextMessage) after).getText()); - - } - - public void testConnectorReAdd() throws Exception { - MessageConsumer remoteConsumer = remoteSession.createConsumer(included); - MessageProducer localProducer = localSession.createProducer(included); - - localProducer.send(localSession.createTextMessage("before")); - Message before = remoteConsumer.receive(1000); - assertNotNull(before); - assertEquals("before", ((TextMessage) before).getText()); - - // restart connector - - // wait for ack back to localbroker with concurrent store and dispatch, dispatch occurs first - Thread.sleep(1000); - - NetworkConnector connector = localBroker.getNetworkConnectorByName("networkConnector"); - - LOG.info("Removing connector"); - connector.stop(); - localBroker.removeNetworkConnector(connector); - - Thread.sleep(5000); - LOG.info("Re-adding connector"); - localBroker.addNetworkConnector(connector); - connector.start(); - - Thread.sleep(5000); - - localProducer.send(localSession.createTextMessage("after")); - Message after = remoteConsumer.receive(3000); - assertNotNull(after); - assertEquals("after", ((TextMessage) after).getText()); - } - - @Override - protected void setUp() throws Exception { - setAutoFail(true); - super.setUp(); - doSetUp(); - } - - @Override - protected void tearDown() throws Exception { - localBroker.deleteAllMessages(); - remoteBroker.deleteAllMessages(); - doTearDown(); - super.tearDown(); - } - - protected void doTearDown() throws Exception { - localConnection.close(); - remoteConnection.close(); - localBroker.stop(); - localBroker.waitUntilStopped(); - remoteBroker.stop(); - remoteBroker.waitUntilStopped(); - } - - protected void doSetUp() throws Exception { - - remoteBroker = createRemoteBroker(); - remoteBroker.start(); - remoteBroker.waitUntilStarted(); - localBroker = createLocalBroker(); - localBroker.start(); - localBroker.waitUntilStarted(); - - String localURI = "tcp://localhost:61616"; - String remoteURI = "tcp://localhost:61617"; - ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(localURI); - localConnection = fac.createConnection(); - localConnection.setClientID("local"); - localConnection.start(); - - fac = new ActiveMQConnectionFactory(remoteURI); - fac.setWatchTopicAdvisories(false); - remoteConnection = fac.createConnection(); - remoteConnection.setClientID("remote"); - remoteConnection.start(); - - localSession = localConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - remoteSession = remoteConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } - - protected String getRemoteBrokerURI() { - return "org/apache/activemq/network/remoteBroker.xml"; - } - - protected String getLocalBrokerURI() { - return "org/apache/activemq/network/localBroker.xml"; - } - - protected BrokerService createBroker(String uri) throws Exception { - Resource resource = new ClassPathResource(uri); - BrokerFactoryBean factory = new BrokerFactoryBean(resource); - resource = new ClassPathResource(uri); - factory = new BrokerFactoryBean(resource); - factory.afterPropertiesSet(); - BrokerService result = factory.getBroker(); - return result; - } - - protected BrokerService createLocalBroker() throws Exception { - return createBroker(getLocalBrokerURI()); - } - - protected BrokerService createRemoteBroker() throws Exception { - return createBroker(getRemoteBrokerURI()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRouteTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRouteTest.java deleted file mode 100644 index f712349c13..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/NetworkRouteTest.java +++ /dev/null @@ -1,342 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network; - -import java.util.Arrays; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.advisory.AdvisorySupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQMessage; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.command.BrokerId; -import org.apache.activemq.command.BrokerInfo; -import org.apache.activemq.command.ConnectionId; -import org.apache.activemq.command.ConsumerId; -import org.apache.activemq.command.ConsumerInfo; -import org.apache.activemq.command.MessageAck; -import org.apache.activemq.command.MessageDispatch; -import org.apache.activemq.command.RemoveInfo; -import org.apache.activemq.command.Response; -import org.apache.activemq.command.SessionId; -import org.apache.activemq.transport.FutureResponse; -import org.apache.activemq.transport.ResponseCallback; -import org.apache.activemq.transport.Transport; -import org.apache.activemq.transport.TransportListener; -import org.easymock.EasyMock; -import org.easymock.IAnswer; -import org.easymock.IMocksControl; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -public class NetworkRouteTest { - - private IMocksControl control; - private BrokerService brokerService; - private Transport localBroker; - private Transport remoteBroker; - private TransportListener localListener; - private TransportListener remoteListener; - private MessageDispatch msgDispatch; - private ActiveMQMessage path1Msg; - private ActiveMQMessage path2Msg; - private ActiveMQMessage removePath1Msg; - private ActiveMQMessage removePath2Msg; - - // this sort of mockery is very brittle but it is fast! - - @Test - public void verifyNoRemoveOnOneConduitRemove() throws Exception { - EasyMock.expect(localBroker.request(EasyMock.isA(ConsumerInfo.class))).andReturn(null); - control.replay(); - - remoteListener.onCommand(path2Msg); - remoteListener.onCommand(path1Msg); - - remoteListener.onCommand(removePath2Msg); - control.verify(); - } - - @Test - public void addAndRemoveOppositeOrder() throws Exception { - // from (1) - localBroker.request(EasyMock.isA(ConsumerInfo.class)); - ArgHolder localConsumer = ArgHolder.holdArgsForLastObjectCall(); - // from (2a) - remoteBroker.asyncRequest(EasyMock.isA(ActiveMQMessage.class), EasyMock.isA(ResponseCallback.class)); - ArgHolder firstMessageFuture = ArgHolder.holdArgsForLastFutureRequestCall(); - localBroker.oneway(EasyMock.isA(MessageAck.class)); - // from (2b) - remoteBroker.asyncRequest(EasyMock.isA(ActiveMQMessage.class), EasyMock.isA(ResponseCallback.class)); - ArgHolder secondMessageFuture = ArgHolder.holdArgsForLastFutureRequestCall(); - - localBroker.oneway(EasyMock.isA(MessageAck.class)); - // from (3) - localBroker.oneway(EasyMock.isA(RemoveInfo.class)); - ExpectationWaiter waitForRemove = ExpectationWaiter.waiterForLastVoidCall(); - control.replay(); - - // (1) send advisory of path 1 - remoteListener.onCommand(path1Msg); - msgDispatch.setConsumerId(((ConsumerInfo) localConsumer.arguments[0]).getConsumerId()); - // send advisory of path 2, doesn't send a ConsumerInfo to localBroker - remoteListener.onCommand(path2Msg); - // (2a) send a message - localListener.onCommand(msgDispatch); - ResponseCallback callback = (ResponseCallback) firstMessageFuture.arguments[1]; - FutureResponse response = new FutureResponse(callback); - response.set(new Response()); - - // send advisory of path 2 remove, doesn't send a RemoveInfo to localBroker - remoteListener.onCommand(removePath2Msg); - // (2b) send a message - localListener.onCommand(msgDispatch); - callback = (ResponseCallback) secondMessageFuture.arguments[1]; - response = new FutureResponse(callback); - response.set(new Response()); - - // (3) send advisory of path 1 remove, sends a RemoveInfo to localBroker - remoteListener.onCommand(removePath1Msg); - waitForRemove.assertHappens(5, TimeUnit.SECONDS); - // send a message, does not send message as in 2a and 2b - localListener.onCommand(msgDispatch); - - control.verify(); - } - - @Test - public void addAndRemoveSameOrder() throws Exception { - // from (1) - localBroker.request(EasyMock.isA(ConsumerInfo.class)); - ArgHolder localConsumer = ArgHolder.holdArgsForLastObjectCall(); - - // from (2a) - remoteBroker.asyncRequest(EasyMock.isA(ActiveMQMessage.class), EasyMock.isA(ResponseCallback.class)); - ArgHolder firstMessageFuture = ArgHolder.holdArgsForLastFutureRequestCall(); - - localBroker.oneway(EasyMock.isA(MessageAck.class)); - - // from (2b) - remoteBroker.asyncRequest(EasyMock.isA(ActiveMQMessage.class), EasyMock.isA(ResponseCallback.class)); - ArgHolder secondMessageFuture = ArgHolder.holdArgsForLastFutureRequestCall(); - - localBroker.oneway(EasyMock.isA(MessageAck.class)); - - // from (3) - localBroker.oneway(EasyMock.isA(RemoveInfo.class)); - ExpectationWaiter waitForRemove = ExpectationWaiter.waiterForLastVoidCall(); - control.replay(); - - // (1) send advisory of path 1 - remoteListener.onCommand(path1Msg); - msgDispatch.setConsumerId(((ConsumerInfo) localConsumer.arguments[0]).getConsumerId()); - // send advisory of path 2, doesn't send a ConsumerInfo to localBroker - remoteListener.onCommand(path2Msg); - // (2a) send a message - localListener.onCommand(msgDispatch); - ResponseCallback callback = (ResponseCallback) firstMessageFuture.arguments[1]; - FutureResponse response = new FutureResponse(callback); - response.set(new Response()); - - // send advisory of path 1 remove, shouldn't send a RemoveInfo to localBroker - remoteListener.onCommand(removePath1Msg); - // (2b) send a message, should send the message as in 2a - localListener.onCommand(msgDispatch); - callback = (ResponseCallback) secondMessageFuture.arguments[1]; - response = new FutureResponse(callback); - response.set(new Response()); - - // (3) send advisory of path 1 remove, should send a RemoveInfo to localBroker - remoteListener.onCommand(removePath2Msg); - waitForRemove.assertHappens(5, TimeUnit.SECONDS); - // send a message, does not send message as in 2a - localListener.onCommand(msgDispatch); - - control.verify(); - } - - @Before - public void before() throws Exception { - control = EasyMock.createControl(); - localBroker = control.createMock(Transport.class); - remoteBroker = control.createMock(Transport.class); - - NetworkBridgeConfiguration configuration = new NetworkBridgeConfiguration(); - brokerService = new BrokerService(); - BrokerInfo remoteBrokerInfo = new BrokerInfo(); - - configuration.setDuplex(true); - configuration.setNetworkTTL(5); - brokerService.setBrokerId("broker-1"); - brokerService.setPersistent(false); - brokerService.setUseJmx(false); - brokerService.start(); - brokerService.waitUntilStarted(); - remoteBrokerInfo.setBrokerId(new BrokerId("remote-broker-id")); - remoteBrokerInfo.setBrokerName("remote-broker-name"); - - localBroker.setTransportListener(EasyMock.isA(TransportListener.class)); - ArgHolder localListenerRef = ArgHolder.holdArgsForLastVoidCall(); - - remoteBroker.setTransportListener(EasyMock.isA(TransportListener.class)); - ArgHolder remoteListenerRef = ArgHolder.holdArgsForLastVoidCall(); - localBroker.start(); - remoteBroker.start(); - - remoteBroker.oneway(EasyMock.isA(Object.class)); - EasyMock.expectLastCall().times(4); - remoteBroker.oneway(EasyMock.isA(Object.class)); - ExpectationWaiter remoteInitWaiter = ExpectationWaiter.waiterForLastVoidCall(); - - localBroker.oneway(remoteBrokerInfo); - EasyMock.expect(localBroker.request(EasyMock.isA(Object.class))).andReturn(null); - localBroker.oneway(EasyMock.isA(Object.class)); - ExpectationWaiter localInitWaiter = ExpectationWaiter.waiterForLastVoidCall(); - - control.replay(); - - DurableConduitBridge bridge = new DurableConduitBridge(configuration, localBroker, remoteBroker); - bridge.setBrokerService(brokerService); - bridge.start(); - - localListener = (TransportListener) localListenerRef.getArguments()[0]; - Assert.assertNotNull(localListener); - remoteListener = (TransportListener) remoteListenerRef.getArguments()[0]; - Assert.assertNotNull(remoteListener); - - remoteListener.onCommand(remoteBrokerInfo); - - remoteInitWaiter.assertHappens(5, TimeUnit.SECONDS); - localInitWaiter.assertHappens(5, TimeUnit.SECONDS); - - control.verify(); - control.reset(); - - ActiveMQMessage msg = new ActiveMQMessage(); - msg.setDestination(new ActiveMQTopic("test")); - msgDispatch = new MessageDispatch(); - msgDispatch.setMessage(msg); - - ConsumerInfo path1 = new ConsumerInfo(); - path1.setDestination(msg.getDestination()); - path1.setConsumerId(new ConsumerId(new SessionId(new ConnectionId("conn-id-1"), 1), 3)); - path1.setBrokerPath(new BrokerId[]{new BrokerId("remote-broker-id"), new BrokerId("server(1)-broker-id"),}); - path1Msg = new ActiveMQMessage(); - path1Msg.setDestination(AdvisorySupport.getConsumerAdvisoryTopic(path1.getDestination())); - path1Msg.setDataStructure(path1); - - ConsumerInfo path2 = new ConsumerInfo(); - path2.setDestination(path1.getDestination()); - path2.setConsumerId(new ConsumerId(new SessionId(new ConnectionId("conn-id-2"), 2), 4)); - path2.setBrokerPath(new BrokerId[]{new BrokerId("remote-broker-id"), new BrokerId("server(2)-broker-id"), new BrokerId("server(1)-broker-id"),}); - path2Msg = new ActiveMQMessage(); - path2Msg.setDestination(path1Msg.getDestination()); - path2Msg.setDataStructure(path2); - - RemoveInfo removePath1 = new RemoveInfo(path1.getConsumerId()); - RemoveInfo removePath2 = new RemoveInfo(path2.getConsumerId()); - - removePath1Msg = new ActiveMQMessage(); - removePath1Msg.setDestination(path1Msg.getDestination()); - removePath1Msg.setDataStructure(removePath1); - - removePath2Msg = new ActiveMQMessage(); - removePath2Msg.setDestination(path1Msg.getDestination()); - removePath2Msg.setDataStructure(removePath2); - } - - @After - public void after() throws Exception { - control.reset(); - brokerService.stop(); - brokerService.waitUntilStopped(); - } - - private static class ArgHolder { - - public Object[] arguments; - - public static ArgHolder holdArgsForLastVoidCall() { - final ArgHolder holder = new ArgHolder(); - EasyMock.expectLastCall().andAnswer(new IAnswer() { - @Override - public Object answer() throws Throwable { - Object[] args = EasyMock.getCurrentArguments(); - holder.arguments = Arrays.copyOf(args, args.length); - return null; - } - }); - return holder; - } - - public static ArgHolder holdArgsForLastObjectCall() { - final ArgHolder holder = new ArgHolder(); - EasyMock.expect(new Object()).andAnswer(new IAnswer() { - @Override - public Object answer() throws Throwable { - Object[] args = EasyMock.getCurrentArguments(); - holder.arguments = Arrays.copyOf(args, args.length); - return null; - } - }); - return holder; - } - - public static ArgHolder holdArgsForLastFutureRequestCall() { - final ArgHolder holder = new ArgHolder(); - EasyMock.expect(new FutureResponse(null)).andAnswer(new IAnswer() { - @Override - public FutureResponse answer() throws Throwable { - Object[] args = EasyMock.getCurrentArguments(); - holder.arguments = Arrays.copyOf(args, args.length); - return null; - } - }); - - return holder; - } - - public Object[] getArguments() { - Assert.assertNotNull(arguments); - return arguments; - } - } - - private static class ExpectationWaiter { - - private CountDownLatch latch = new CountDownLatch(1); - - public static ExpectationWaiter waiterForLastVoidCall() { - final ExpectationWaiter waiter = new ExpectationWaiter(); - EasyMock.expectLastCall().andAnswer(new IAnswer() { - @Override - public Object answer() throws Throwable { - waiter.latch.countDown(); - return null; - } - }); - return waiter; - } - - public void assertHappens(long timeout, TimeUnit unit) throws InterruptedException { - Assert.assertTrue(latch.await(timeout, unit)); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/SSHTunnelNetworkReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/SSHTunnelNetworkReconnectTest.java deleted file mode 100644 index a07f8210e7..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/SSHTunnelNetworkReconnectTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.util.ArrayList; - -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; - -/** - * Test network reconnects over SSH tunnels. This case can be especially tricky - * since the SSH tunnels fool the TCP transport into thinking that they are - * initially connected. - */ -public class SSHTunnelNetworkReconnectTest extends NetworkReconnectTest { - - ArrayList processes = new ArrayList<>(); - - @Override - protected BrokerService createFirstBroker() throws Exception { - return BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/network/ssh-reconnect-broker1.xml")); - } - - @Override - protected BrokerService createSecondBroker() throws Exception { - return BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/network/ssh-reconnect-broker2.xml")); - } - - @Override - protected void setUp() throws Exception { - startProcess("ssh -Nn -L60006:localhost:61616 localhost"); - startProcess("ssh -Nn -L60007:localhost:61617 localhost"); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - for (Process p : processes) { - p.destroy(); - } - } - - private void startProcess(String command) throws IOException { - final Process process = Runtime.getRuntime().exec(command); - processes.add(process); - new Thread("stdout: " + command) { - @Override - public void run() { - try { - InputStream is = process.getInputStream(); - int c; - while ((c = is.read()) >= 0) { - System.out.write(c); - } - } catch (IOException e) { - } - } - }.start(); - new Thread("stderr: " + command) { - @Override - public void run() { - try { - InputStream is = process.getErrorStream(); - int c; - while ((c = is.read()) >= 0) { - System.err.write(c); - } - } catch (IOException e) { - } - } - }.start(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/SimpleNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/SimpleNetworkTest.java deleted file mode 100644 index b5005021c5..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/SimpleNetworkTest.java +++ /dev/null @@ -1,322 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.jms.TopicRequestor; -import javax.jms.TopicSession; -import java.net.URI; -import java.util.Arrays; -import java.util.concurrent.ConcurrentMap; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQMessage; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.command.ConsumerId; -import org.apache.activemq.util.Wait; -import org.apache.activemq.xbean.BrokerFactoryBean; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.support.AbstractApplicationContext; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -public class SimpleNetworkTest { - - protected static final int MESSAGE_COUNT = 10; - private static final Logger LOG = LoggerFactory.getLogger(SimpleNetworkTest.class); - - protected AbstractApplicationContext context; - protected Connection localConnection; - protected Connection remoteConnection; - protected BrokerService localBroker; - protected BrokerService remoteBroker; - protected Session localSession; - protected Session remoteSession; - protected ActiveMQTopic included; - protected ActiveMQTopic excluded; - protected String consumerName = "durableSubs"; - - // works b/c of non marshaling vm transport, the connection - // ref from the client is used during the forward - @Test(timeout = 60 * 1000) - public void testMessageCompression() throws Exception { - - ActiveMQConnection localAmqConnection = (ActiveMQConnection) localConnection; - localAmqConnection.setUseCompression(true); - - MessageConsumer consumer1 = remoteSession.createConsumer(included); - MessageProducer producer = localSession.createProducer(included); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - - waitForConsumerRegistration(localBroker, 1, included); - - for (int i = 0; i < MESSAGE_COUNT; i++) { - Message test = localSession.createTextMessage("test-" + i); - producer.send(test); - Message msg = consumer1.receive(3000); - assertNotNull(msg); - ActiveMQMessage amqMessage = (ActiveMQMessage) msg; - assertTrue(amqMessage.isCompressed()); - } - // ensure no more messages received - assertNull(consumer1.receive(1000)); - } - - @Test(timeout = 60 * 1000) - public void testRequestReply() throws Exception { - final MessageProducer remoteProducer = remoteSession.createProducer(null); - MessageConsumer remoteConsumer = remoteSession.createConsumer(included); - remoteConsumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message msg) { - try { - TextMessage textMsg = (TextMessage) msg; - String payload = "REPLY: " + textMsg.getText(); - Destination replyTo; - replyTo = msg.getJMSReplyTo(); - textMsg.clearBody(); - textMsg.setText(payload); - remoteProducer.send(replyTo, textMsg); - } catch (JMSException e) { - e.printStackTrace(); - } - } - }); - - TopicRequestor requestor = new TopicRequestor((TopicSession) localSession, included); - // allow for consumer infos to perculate around - Thread.sleep(5000); - for (int i = 0; i < MESSAGE_COUNT; i++) { - TextMessage msg = localSession.createTextMessage("test msg: " + i); - TextMessage result = (TextMessage) requestor.request(msg); - assertNotNull(result); - LOG.info(result.getText()); - } - } - - @Test(timeout = 60 * 1000) - public void testFiltering() throws Exception { - MessageConsumer includedConsumer = remoteSession.createConsumer(included); - MessageConsumer excludedConsumer = remoteSession.createConsumer(excluded); - MessageProducer includedProducer = localSession.createProducer(included); - MessageProducer excludedProducer = localSession.createProducer(excluded); - // allow for consumer infos to perculate around - Thread.sleep(2000); - Message test = localSession.createTextMessage("test"); - includedProducer.send(test); - excludedProducer.send(test); - assertNull(excludedConsumer.receive(1000)); - assertNotNull(includedConsumer.receive(1000)); - } - - @Test(timeout = 60 * 1000) - public void testConduitBridge() throws Exception { - MessageConsumer consumer1 = remoteSession.createConsumer(included); - MessageConsumer consumer2 = remoteSession.createConsumer(included); - MessageProducer producer = localSession.createProducer(included); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - - waitForConsumerRegistration(localBroker, 2, included); - - for (int i = 0; i < MESSAGE_COUNT; i++) { - Message test = localSession.createTextMessage("test-" + i); - producer.send(test); - assertNotNull(consumer1.receive(1000)); - assertNotNull(consumer2.receive(1000)); - } - // ensure no more messages received - assertNull(consumer1.receive(1000)); - assertNull(consumer2.receive(1000)); - } - - private void waitForConsumerRegistration(final BrokerService brokerService, - final int min, - final ActiveMQDestination destination) throws Exception { - assertTrue("Internal bridge consumers registered in time", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Object[] bridges = brokerService.getNetworkConnectors().get(0).bridges.values().toArray(); - if (bridges.length > 0) { - LOG.info(brokerService + " bridges " + Arrays.toString(bridges)); - DemandForwardingBridgeSupport demandForwardingBridgeSupport = (DemandForwardingBridgeSupport) bridges[0]; - ConcurrentMap forwardingBridges = demandForwardingBridgeSupport.getLocalSubscriptionMap(); - LOG.info(brokerService + " bridge " + demandForwardingBridgeSupport + ", localSubs: " + forwardingBridges); - if (!forwardingBridges.isEmpty()) { - for (DemandSubscription demandSubscription : forwardingBridges.values()) { - if (demandSubscription.getLocalInfo().getDestination().equals(destination)) { - LOG.info(brokerService + " DemandSubscription " + demandSubscription + ", size: " + demandSubscription.size()); - return demandSubscription.size() >= min; - } - } - } - } - return false; - } - })); - } - - @Test(timeout = 60 * 1000) - public void testDurableStoreAndForward() throws Exception { - // create a remote durable consumer - MessageConsumer remoteConsumer = remoteSession.createDurableSubscriber(included, consumerName); - Thread.sleep(1000); - // now close everything down and restart - doTearDown(); - doSetUp(false); - MessageProducer producer = localSession.createProducer(included); - for (int i = 0; i < MESSAGE_COUNT; i++) { - Message test = localSession.createTextMessage("test-" + i); - producer.send(test); - } - Thread.sleep(1000); - // close everything down and restart - doTearDown(); - doSetUp(false); - remoteConsumer = remoteSession.createDurableSubscriber(included, consumerName); - for (int i = 0; i < MESSAGE_COUNT; i++) { - assertNotNull("message count: " + i, remoteConsumer.receive(2500)); - } - } - - @Ignore("This seems like a simple use case, but it is problematic to consume an existing topic store, " + "it requires a connection per durable to match that connectionId") - public void testDurableStoreAndForwardReconnect() throws Exception { - // create a local durable consumer - MessageConsumer localConsumer = localSession.createDurableSubscriber(included, consumerName); - Thread.sleep(5000); - // now close everything down and restart - doTearDown(); - doSetUp(false); - // send messages - MessageProducer producer = localSession.createProducer(included); - for (int i = 0; i < MESSAGE_COUNT; i++) { - Message test = localSession.createTextMessage("test-" + i); - producer.send(test); - } - Thread.sleep(5000); - // consume some messages locally - localConsumer = localSession.createDurableSubscriber(included, consumerName); - LOG.info("Consume from local consumer: " + localConsumer); - for (int i = 0; i < MESSAGE_COUNT / 2; i++) { - assertNotNull("message count: " + i, localConsumer.receive(2500)); - } - Thread.sleep(5000); - // close everything down and restart - doTearDown(); - doSetUp(false); - Thread.sleep(5000); - - LOG.info("Consume from remote"); - // consume the rest remotely - MessageConsumer remoteConsumer = remoteSession.createDurableSubscriber(included, consumerName); - LOG.info("Remote consumer: " + remoteConsumer); - Thread.sleep(5000); - for (int i = 0; i < MESSAGE_COUNT / 2; i++) { - assertNotNull("message count: " + i, remoteConsumer.receive(10000)); - } - } - - @Before - public void setUp() throws Exception { - doSetUp(true); - } - - @After - public void tearDown() throws Exception { - doTearDown(); - } - - protected void doTearDown() throws Exception { - localConnection.close(); - remoteConnection.close(); - localBroker.stop(); - remoteBroker.stop(); - } - - protected void doSetUp(boolean deleteAllMessages) throws Exception { - remoteBroker = createRemoteBroker(); - remoteBroker.setDeleteAllMessagesOnStartup(deleteAllMessages); - remoteBroker.start(); - remoteBroker.waitUntilStarted(); - localBroker = createLocalBroker(); - localBroker.setDeleteAllMessagesOnStartup(deleteAllMessages); - localBroker.start(); - localBroker.waitUntilStarted(); - URI localURI = localBroker.getVmConnectorURI(); - ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(localURI); - fac.setAlwaysSyncSend(true); - fac.setDispatchAsync(false); - localConnection = fac.createConnection(); - localConnection.setClientID("clientId"); - localConnection.start(); - URI remoteURI = remoteBroker.getVmConnectorURI(); - fac = new ActiveMQConnectionFactory(remoteURI); - remoteConnection = fac.createConnection(); - remoteConnection.setClientID("clientId"); - remoteConnection.start(); - included = new ActiveMQTopic("include.test.bar"); - excluded = new ActiveMQTopic("exclude.test.bar"); - localSession = localConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - remoteSession = remoteConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } - - protected String getRemoteBrokerURI() { - return "org/apache/activemq/network/remoteBroker.xml"; - } - - protected String getLocalBrokerURI() { - return "org/apache/activemq/network/localBroker.xml"; - } - - protected BrokerService createBroker(String uri) throws Exception { - Resource resource = new ClassPathResource(uri); - BrokerFactoryBean factory = new BrokerFactoryBean(resource); - resource = new ClassPathResource(uri); - factory = new BrokerFactoryBean(resource); - factory.afterPropertiesSet(); - BrokerService result = factory.getBroker(); - return result; - } - - protected BrokerService createLocalBroker() throws Exception { - return createBroker(getLocalBrokerURI()); - } - - protected BrokerService createRemoteBroker() throws Exception { - return createBroker(getRemoteBrokerURI()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/duplexDynamicIncludedDestLocalBroker.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/duplexDynamicIncludedDestLocalBroker.xml deleted file mode 100644 index 70f6da8215..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/duplexDynamicIncludedDestLocalBroker.xml +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/duplexLocalBroker.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/duplexLocalBroker.xml deleted file mode 100644 index 17268c37f1..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/duplexLocalBroker.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeStandaloneReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeStandaloneReconnectTest.java deleted file mode 100644 index 04c416fb01..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeStandaloneReconnectTest.java +++ /dev/null @@ -1,365 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network.jms; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.util.ArrayList; -import java.util.Iterator; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.util.Wait; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertTrue; - -public class QueueBridgeStandaloneReconnectTest { - - private SimpleJmsQueueConnector jmsQueueConnector; - - private BrokerService localBroker; - private BrokerService foreignBroker; - - private ActiveMQConnectionFactory localConnectionFactory; - private ActiveMQConnectionFactory foreignConnectionFactory; - - private Destination outbound; - private Destination inbound; - - private final ArrayList connections = new ArrayList<>(); - - @Test(timeout = 60 * 1000) - public void testSendAndReceiveOverConnectedBridges() throws Exception { - - startLocalBroker(); - startForeignBroker(); - - jmsQueueConnector.start(); - - sendMessageToForeignBroker("to.foreign.broker"); - sendMessageToLocalBroker("to.local.broker"); - - final MessageConsumer local = createConsumerForLocalBroker(); - - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = local.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.local.broker")) { - return true; - } - return false; - } - })); - - final MessageConsumer foreign = createConsumerForForeignBroker(); - - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = foreign.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.foreign.broker")) { - return true; - } - return false; - } - })); - } - - @Test(timeout = 60 * 1000) - public void testSendAndReceiveOverBridgeWhenStartedBeforeBrokers() throws Exception { - - jmsQueueConnector.start(); - - startLocalBroker(); - startForeignBroker(); - - assertTrue("Should have Connected.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return jmsQueueConnector.isConnected(); - } - })); - - sendMessageToForeignBroker("to.foreign.broker"); - sendMessageToLocalBroker("to.local.broker"); - - final MessageConsumer local = createConsumerForLocalBroker(); - - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = local.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.local.broker")) { - return true; - } - return false; - } - })); - - final MessageConsumer foreign = createConsumerForForeignBroker(); - - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = foreign.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.foreign.broker")) { - return true; - } - return false; - } - })); - } - - @Test(timeout = 60 * 1000) - public void testSendAndReceiveOverBridgeWithRestart() throws Exception { - - startLocalBroker(); - startForeignBroker(); - - jmsQueueConnector.start(); - - assertTrue("Should have Connected.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return jmsQueueConnector.isConnected(); - } - })); - - stopLocalBroker(); - stopForeignBroker(); - - assertTrue("Should have detected connection drop.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return !jmsQueueConnector.isConnected(); - } - })); - - startLocalBroker(); - startForeignBroker(); - - assertTrue("Should have Re-Connected.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return jmsQueueConnector.isConnected(); - } - })); - - sendMessageToForeignBroker("to.foreign.broker"); - sendMessageToLocalBroker("to.local.broker"); - - final MessageConsumer local = createConsumerForLocalBroker(); - - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = local.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.local.broker")) { - return true; - } - return false; - } - })); - - final MessageConsumer foreign = createConsumerForForeignBroker(); - - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = foreign.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.foreign.broker")) { - return true; - } - return false; - } - })); - } - - @Before - public void setUp() throws Exception { - - localConnectionFactory = createLocalConnectionFactory(); - foreignConnectionFactory = createForeignConnectionFactory(); - - outbound = new ActiveMQQueue("RECONNECT.TEST.OUT.QUEUE"); - inbound = new ActiveMQQueue("RECONNECT.TEST.IN.QUEUE"); - - jmsQueueConnector = new SimpleJmsQueueConnector(); - - // Wire the bridges. - jmsQueueConnector.setOutboundQueueBridges(new OutboundQueueBridge[]{new OutboundQueueBridge("RECONNECT.TEST.OUT.QUEUE")}); - jmsQueueConnector.setInboundQueueBridges(new InboundQueueBridge[]{new InboundQueueBridge("RECONNECT.TEST.IN.QUEUE")}); - - // Tell it how to reach the two brokers. - jmsQueueConnector.setOutboundQueueConnectionFactory(new ActiveMQConnectionFactory("tcp://localhost:61617")); - jmsQueueConnector.setLocalQueueConnectionFactory(new ActiveMQConnectionFactory("tcp://localhost:61616")); - } - - @After - public void tearDown() throws Exception { - disposeConsumerConnections(); - - try { - jmsQueueConnector.stop(); - jmsQueueConnector = null; - } catch (Exception e) { - } - - try { - stopLocalBroker(); - } catch (Throwable e) { - } - try { - stopForeignBroker(); - } catch (Throwable e) { - } - } - - protected void disposeConsumerConnections() { - for (Iterator iter = connections.iterator(); iter.hasNext(); ) { - Connection connection = iter.next(); - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } - - protected void startLocalBroker() throws Exception { - if (localBroker == null) { - localBroker = createFirstBroker(); - localBroker.start(); - localBroker.waitUntilStarted(); - } - } - - protected void stopLocalBroker() throws Exception { - if (localBroker != null) { - localBroker.stop(); - localBroker.waitUntilStopped(); - localBroker = null; - } - } - - protected void startForeignBroker() throws Exception { - if (foreignBroker == null) { - foreignBroker = createSecondBroker(); - foreignBroker.start(); - foreignBroker.waitUntilStarted(); - } - } - - protected void stopForeignBroker() throws Exception { - if (foreignBroker != null) { - foreignBroker.stop(); - foreignBroker.waitUntilStopped(); - foreignBroker = null; - } - } - - protected BrokerService createFirstBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("broker1"); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://localhost:61616"); - - return broker; - } - - protected BrokerService createSecondBroker() throws Exception { - - BrokerService broker = new BrokerService(); - broker.setBrokerName("broker2"); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://localhost:61617"); - - return broker; - } - - protected ActiveMQConnectionFactory createLocalConnectionFactory() { - return new ActiveMQConnectionFactory("tcp://localhost:61616"); - } - - protected ActiveMQConnectionFactory createForeignConnectionFactory() { - return new ActiveMQConnectionFactory("tcp://localhost:61617"); - } - - protected void sendMessageToForeignBroker(String text) throws JMSException { - Connection connection = null; - try { - connection = localConnectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(outbound); - TextMessage message = session.createTextMessage(); - message.setText(text); - producer.send(message); - } finally { - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } - - protected void sendMessageToLocalBroker(String text) throws JMSException { - Connection connection = null; - try { - connection = foreignConnectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(inbound); - TextMessage message = session.createTextMessage(); - message.setText(text); - producer.send(message); - } finally { - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } - - protected MessageConsumer createConsumerForLocalBroker() throws JMSException { - Connection connection = localConnectionFactory.createConnection(); - connections.add(connection); - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - return session.createConsumer(inbound); - } - - protected MessageConsumer createConsumerForForeignBroker() throws JMSException { - Connection connection = foreignConnectionFactory.createConnection(); - connections.add(connection); - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - return session.createConsumer(outbound); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeTest.java deleted file mode 100644 index e53025c73d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeTest.java +++ /dev/null @@ -1,114 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network.jms; - -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.QueueConnection; -import javax.jms.QueueRequestor; -import javax.jms.QueueSession; -import javax.jms.Session; -import javax.jms.TextMessage; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.support.AbstractApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class QueueBridgeTest extends TestCase implements MessageListener { - - protected static final int MESSAGE_COUNT = 10; - private static final Logger LOG = LoggerFactory.getLogger(QueueBridgeTest.class); - - protected AbstractApplicationContext context; - protected QueueConnection localConnection; - protected QueueConnection remoteConnection; - protected QueueRequestor requestor; - protected QueueSession requestServerSession; - protected MessageConsumer requestServerConsumer; - protected MessageProducer requestServerProducer; - - @Override - protected void setUp() throws Exception { - super.setUp(); - context = createApplicationContext(); - - createConnections(); - - requestServerSession = localConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); - Queue theQueue = requestServerSession.createQueue(getClass().getName()); - requestServerConsumer = requestServerSession.createConsumer(theQueue); - requestServerConsumer.setMessageListener(this); - requestServerProducer = requestServerSession.createProducer(null); - - QueueSession session = remoteConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); - requestor = new QueueRequestor(session, theQueue); - } - - protected void createConnections() throws JMSException { - ActiveMQConnectionFactory fac = (ActiveMQConnectionFactory) context.getBean("localFactory"); - localConnection = fac.createQueueConnection(); - localConnection.start(); - - fac = (ActiveMQConnectionFactory) context.getBean("remoteFactory"); - remoteConnection = fac.createQueueConnection(); - remoteConnection.start(); - } - - protected AbstractApplicationContext createApplicationContext() { - return new ClassPathXmlApplicationContext("org/apache/activemq/network/jms/queue-config.xml"); - } - - @Override - protected void tearDown() throws Exception { - localConnection.close(); - super.tearDown(); - } - - public void testQueueRequestorOverBridge() throws JMSException { - for (int i = 0; i < MESSAGE_COUNT; i++) { - TextMessage msg = requestServerSession.createTextMessage("test msg: " + i); - TextMessage result = (TextMessage) requestor.request(msg); - assertNotNull(result); - LOG.info(result.getText()); - } - } - - @Override - public void onMessage(Message msg) { - try { - TextMessage textMsg = (TextMessage) msg; - String payload = "REPLY: " + textMsg.getText(); - Destination replyTo; - replyTo = msg.getJMSReplyTo(); - textMsg.clearBody(); - textMsg.setText(payload); - requestServerProducer.send(replyTo, textMsg); - } catch (JMSException e) { - e.printStackTrace(); - } - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeXBeanTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeXBeanTest.java deleted file mode 100644 index ac31262525..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueBridgeXBeanTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network.jms; - -import org.apache.xbean.spring.context.ClassPathXmlApplicationContext; -import org.springframework.context.support.AbstractApplicationContext; - -/** - * - * - */ -public class QueueBridgeXBeanTest extends QueueBridgeTest { - - @Override - protected AbstractApplicationContext createApplicationContext() { - return new ClassPathXmlApplicationContext("org/apache/activemq/network/jms/queue-xbean.xml"); - } - - /* - protected void createConnections() throws JMSException { - ActiveMQConnectionFactory fac = (ActiveMQConnectionFactory) context.getBean("localFactory"); - localConnection = fac.createQueueConnection(); - localConnection.start(); - - fac = (ActiveMQConnectionFactory) context.getBean("remoteFactory"); - remoteConnection = fac.createQueueConnection(); - remoteConnection.start(); - } - */ - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueOutboundBridgeReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueOutboundBridgeReconnectTest.java deleted file mode 100644 index be6d2eee85..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/QueueOutboundBridgeReconnectTest.java +++ /dev/null @@ -1,342 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network.jms; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.util.Wait; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -/** - * These test cases are used to verify that queue outbound bridge connections get - * re-established in all broker restart scenarios. This is possible when the - * outbound bridge is configured using the failover URI with a timeout. - */ -public class QueueOutboundBridgeReconnectTest { - - private BrokerService producerBroker; - private BrokerService consumerBroker; - private ActiveMQConnectionFactory producerConnectionFactory; - private ActiveMQConnectionFactory consumerConnectionFactory; - private Destination destination; - private final ArrayList connections = new ArrayList<>(); - - @Test - public void testMultipleProducerBrokerRestarts() throws Exception { - for (int i = 0; i < 10; i++) { - testWithProducerBrokerRestart(); - disposeConsumerConnections(); - } - } - - @Test - public void testRestartProducerWithNoConsumer() throws Exception { - stopConsumerBroker(); - - startProducerBroker(); - sendMessage("test123"); - sendMessage("test456"); - } - - @Test - public void testWithoutRestartsConsumerFirst() throws Exception { - startConsumerBroker(); - startProducerBroker(); - sendMessage("test123"); - sendMessage("test456"); - - MessageConsumer consumer = createConsumer(); - Message message = consumer.receive(3000); - assertNotNull(message); - assertEquals("test123", ((TextMessage) message).getText()); - - message = consumer.receive(3000); - assertNotNull(message); - assertEquals("test456", ((TextMessage) message).getText()); - - assertNull(consumer.receiveNoWait()); - } - - @Test - public void testWithoutRestartsProducerFirst() throws Exception { - startProducerBroker(); - sendMessage("test123"); - - startConsumerBroker(); - - // unless using a failover URI, the first attempt of this send will likely fail, - // so increase the timeout below to give the bridge time to recover - sendMessage("test456"); - - MessageConsumer consumer = createConsumer(); - Message message = consumer.receive(5000); - assertNotNull(message); - assertEquals("test123", ((TextMessage) message).getText()); - - message = consumer.receive(5000); - assertNotNull(message); - assertEquals("test456", ((TextMessage) message).getText()); - - assertNull(consumer.receiveNoWait()); - } - - @Test - public void testWithProducerBrokerRestart() throws Exception { - startProducerBroker(); - startConsumerBroker(); - - sendMessage("test123"); - - MessageConsumer consumer = createConsumer(); - Message message = consumer.receive(5000); - assertNotNull(message); - assertEquals("test123", ((TextMessage) message).getText()); - assertNull(consumer.receiveNoWait()); - - // Restart the first broker... - stopProducerBroker(); - startProducerBroker(); - - sendMessage("test123"); - message = consumer.receive(5000); - assertNotNull(message); - assertEquals("test123", ((TextMessage) message).getText()); - assertNull(consumer.receiveNoWait()); - } - - @Test - public void testWithConsumerBrokerRestart() throws Exception { - - startProducerBroker(); - startConsumerBroker(); - - sendMessage("test123"); - - final MessageConsumer consumer1 = createConsumer(); - Message message = consumer1.receive(5000); - assertNotNull(message); - assertEquals("test123", ((TextMessage) message).getText()); - assertNull(consumer1.receiveNoWait()); - consumer1.close(); - - // Restart the first broker... - stopConsumerBroker(); - startConsumerBroker(); - - // unless using a failover URI, the first attempt of this send will likely fail, - // so increase the timeout below to give the bridge time to recover - sendMessage("test123"); - - final MessageConsumer consumer2 = createConsumer(); - assertTrue("Expected recover and delivery failed", Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - Message message = consumer2.receiveNoWait(); - if (message == null || !((TextMessage) message).getText().equals("test123")) { - return false; - } - return true; - } - })); - assertNull(consumer2.receiveNoWait()); - } - - @Test - public void testWithConsumerBrokerStartDelay() throws Exception { - - startConsumerBroker(); - final MessageConsumer consumer = createConsumer(); - - TimeUnit.SECONDS.sleep(5); - - startProducerBroker(); - - sendMessage("test123"); - assertTrue("Expected recover and delivery failed", Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - Message message = consumer.receiveNoWait(); - if (message == null || !((TextMessage) message).getText().equals("test123")) { - return false; - } - return true; - } - })); - assertNull(consumer.receiveNoWait()); - } - - @Test - public void testWithProducerBrokerStartDelay() throws Exception { - - startProducerBroker(); - - TimeUnit.SECONDS.sleep(5); - - startConsumerBroker(); - MessageConsumer consumer = createConsumer(); - - sendMessage("test123"); - Message message = consumer.receive(5000); - assertNotNull(message); - assertEquals("test123", ((TextMessage) message).getText()); - assertNull(consumer.receiveNoWait()); - } - - @Before - public void setUp() throws Exception { - - producerConnectionFactory = createProducerConnectionFactory(); - consumerConnectionFactory = createConsumerConnectionFactory(); - destination = new ActiveMQQueue("RECONNECT.TEST.QUEUE"); - } - - @After - public void tearDown() throws Exception { - disposeConsumerConnections(); - try { - stopProducerBroker(); - } catch (Throwable e) { - } - try { - stopConsumerBroker(); - } catch (Throwable e) { - } - } - - protected void disposeConsumerConnections() { - for (Iterator iter = connections.iterator(); iter.hasNext(); ) { - Connection connection = iter.next(); - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } - - protected void startProducerBroker() throws Exception { - if (producerBroker == null) { - producerBroker = createFirstBroker(); - producerBroker.start(); - } - } - - protected void stopProducerBroker() throws Exception { - if (producerBroker != null) { - producerBroker.stop(); - producerBroker = null; - } - } - - protected void startConsumerBroker() throws Exception { - if (consumerBroker == null) { - consumerBroker = createSecondBroker(); - consumerBroker.start(); - } - } - - protected void stopConsumerBroker() throws Exception { - if (consumerBroker != null) { - consumerBroker.stop(); - consumerBroker = null; - } - } - - protected BrokerService createFirstBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("broker1"); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://localhost:61616"); - broker.addConnector("vm://broker1"); - - SimpleJmsQueueConnector jmsQueueConnector = new SimpleJmsQueueConnector(); - jmsQueueConnector.setOutboundQueueBridges(new OutboundQueueBridge[]{new OutboundQueueBridge("RECONNECT.TEST.QUEUE")}); - jmsQueueConnector.setOutboundQueueConnectionFactory(new ActiveMQConnectionFactory("tcp://localhost:61617")); - - broker.setJmsBridgeConnectors(new JmsConnector[]{jmsQueueConnector}); - - return broker; - } - - protected BrokerService createSecondBroker() throws Exception { - - BrokerService broker = new BrokerService(); - broker.setBrokerName("broker2"); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://localhost:61617"); - broker.addConnector("vm://broker2"); - - return broker; - } - - protected ActiveMQConnectionFactory createProducerConnectionFactory() { - return new ActiveMQConnectionFactory("vm://broker1"); - } - - protected ActiveMQConnectionFactory createConsumerConnectionFactory() { - return new ActiveMQConnectionFactory("vm://broker2"); - } - - protected void sendMessage(String text) throws JMSException { - Connection connection = null; - try { - connection = producerConnectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage(); - message.setText(text); - producer.send(message); - } finally { - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } - - protected MessageConsumer createConsumer() throws JMSException { - Connection connection = consumerConnectionFactory.createConnection(); - connections.add(connection); - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - return session.createConsumer(destination); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeSpringTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeSpringTest.java deleted file mode 100644 index 9c00180b95..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeSpringTest.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.activemq.network.jms; - -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.jms.Topic; -import javax.jms.TopicConnection; -import javax.jms.TopicRequestor; -import javax.jms.TopicSession; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.support.AbstractApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class TopicBridgeSpringTest extends TestCase implements MessageListener { - - protected static final int MESSAGE_COUNT = 10; - private static final Logger LOG = LoggerFactory.getLogger(TopicBridgeSpringTest.class); - - protected AbstractApplicationContext context; - protected TopicConnection localConnection; - protected TopicConnection remoteConnection; - protected TopicRequestor requestor; - protected TopicSession requestServerSession; - protected MessageConsumer requestServerConsumer; - protected MessageProducer requestServerProducer; - - @Override - protected void setUp() throws Exception { - - super.setUp(); - context = createApplicationContext(); - ActiveMQConnectionFactory fac = (ActiveMQConnectionFactory) context.getBean("localFactory"); - localConnection = fac.createTopicConnection(); - localConnection.start(); - requestServerSession = localConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - Topic theTopic = requestServerSession.createTopic(getClass().getName()); - requestServerConsumer = requestServerSession.createConsumer(theTopic); - requestServerConsumer.setMessageListener(this); - requestServerProducer = requestServerSession.createProducer(null); - - fac = (ActiveMQConnectionFactory) context.getBean("remoteFactory"); - remoteConnection = fac.createTopicConnection(); - remoteConnection.start(); - TopicSession session = remoteConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - requestor = new TopicRequestor(session, theTopic); - } - - protected AbstractApplicationContext createApplicationContext() { - return new ClassPathXmlApplicationContext("org/apache/activemq/network/jms/topic-spring.xml"); - } - - @Override - protected void tearDown() throws Exception { - localConnection.close(); - super.tearDown(); - } - - public void testTopicRequestorOverBridge() throws JMSException { - for (int i = 0; i < MESSAGE_COUNT; i++) { - TextMessage msg = requestServerSession.createTextMessage("test msg: " + i); - LOG.info("Making request: " + msg); - TextMessage result = (TextMessage) requestor.request(msg); - assertNotNull(result); - LOG.info("Received result: " + result.getText()); - } - } - - @Override - public void onMessage(Message msg) { - try { - TextMessage textMsg = (TextMessage) msg; - String payload = "REPLY: " + textMsg.getText(); - Destination replyTo; - replyTo = msg.getJMSReplyTo(); - textMsg.clearBody(); - textMsg.setText(payload); - LOG.info("Sending response: " + textMsg); - requestServerProducer.send(replyTo, textMsg); - } catch (JMSException e) { - e.printStackTrace(); - } - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeStandaloneReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeStandaloneReconnectTest.java deleted file mode 100644 index 81f7d9380b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeStandaloneReconnectTest.java +++ /dev/null @@ -1,362 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.network.jms; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.util.ArrayList; -import java.util.Iterator; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.util.Wait; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertTrue; - -public class TopicBridgeStandaloneReconnectTest { - - private SimpleJmsTopicConnector jmsTopicConnector; - - private BrokerService localBroker; - private BrokerService foreignBroker; - - private ActiveMQConnectionFactory localConnectionFactory; - private ActiveMQConnectionFactory foreignConnectionFactory; - - private Destination outbound; - private Destination inbound; - - private final ArrayList connections = new ArrayList<>(); - - @Test - public void testSendAndReceiveOverConnectedBridges() throws Exception { - - startLocalBroker(); - startForeignBroker(); - - jmsTopicConnector.start(); - - final MessageConsumer local = createConsumerForLocalBroker(); - final MessageConsumer foreign = createConsumerForForeignBroker(); - - sendMessageToForeignBroker("to.foreign.broker"); - sendMessageToLocalBroker("to.local.broker"); - - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = local.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.local.broker")) { - return true; - } - return false; - } - })); - - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = foreign.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.foreign.broker")) { - return true; - } - return false; - } - })); - } - - @Test - public void testSendAndReceiveOverBridgeWhenStartedBeforeBrokers() throws Exception { - - jmsTopicConnector.start(); - - startLocalBroker(); - startForeignBroker(); - - assertTrue("Should have Connected.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return jmsTopicConnector.isConnected(); - } - })); - - final MessageConsumer local = createConsumerForLocalBroker(); - final MessageConsumer foreign = createConsumerForForeignBroker(); - - sendMessageToForeignBroker("to.foreign.broker"); - sendMessageToLocalBroker("to.local.broker"); - - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = local.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.local.broker")) { - return true; - } - return false; - } - })); - - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = foreign.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.foreign.broker")) { - return true; - } - return false; - } - })); - } - - @Test - public void testSendAndReceiveOverBridgeWithRestart() throws Exception { - - startLocalBroker(); - startForeignBroker(); - - jmsTopicConnector.start(); - - assertTrue("Should have Connected.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return jmsTopicConnector.isConnected(); - } - })); - - stopLocalBroker(); - stopForeignBroker(); - - assertTrue("Should have detected connection drop.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return !jmsTopicConnector.isConnected(); - } - })); - - startLocalBroker(); - startForeignBroker(); - - assertTrue("Should have Re-Connected.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return jmsTopicConnector.isConnected(); - } - })); - - final MessageConsumer local = createConsumerForLocalBroker(); - final MessageConsumer foreign = createConsumerForForeignBroker(); - - sendMessageToForeignBroker("to.foreign.broker"); - sendMessageToLocalBroker("to.local.broker"); - - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = local.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.local.broker")) { - return true; - } - return false; - } - })); - - assertTrue("Should have received a Message.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Message message = foreign.receive(100); - if (message != null && ((TextMessage) message).getText().equals("to.foreign.broker")) { - return true; - } - return false; - } - })); - } - - @Before - public void setUp() throws Exception { - - localConnectionFactory = createLocalConnectionFactory(); - foreignConnectionFactory = createForeignConnectionFactory(); - - outbound = new ActiveMQTopic("RECONNECT.TEST.OUT.TOPIC"); - inbound = new ActiveMQTopic("RECONNECT.TEST.IN.TOPIC"); - - jmsTopicConnector = new SimpleJmsTopicConnector(); - - // Wire the bridges. - jmsTopicConnector.setOutboundTopicBridges(new OutboundTopicBridge[]{new OutboundTopicBridge("RECONNECT.TEST.OUT.TOPIC")}); - jmsTopicConnector.setInboundTopicBridges(new InboundTopicBridge[]{new InboundTopicBridge("RECONNECT.TEST.IN.TOPIC")}); - - // Tell it how to reach the two brokers. - jmsTopicConnector.setOutboundTopicConnectionFactory(new ActiveMQConnectionFactory("tcp://localhost:61617")); - jmsTopicConnector.setLocalTopicConnectionFactory(new ActiveMQConnectionFactory("tcp://localhost:61616")); - } - - @After - public void tearDown() throws Exception { - disposeConsumerConnections(); - - try { - jmsTopicConnector.stop(); - jmsTopicConnector = null; - } catch (Exception e) { - } - - try { - stopLocalBroker(); - } catch (Throwable e) { - } - try { - stopForeignBroker(); - } catch (Throwable e) { - } - } - - protected void disposeConsumerConnections() { - for (Iterator iter = connections.iterator(); iter.hasNext(); ) { - Connection connection = iter.next(); - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } - - protected void startLocalBroker() throws Exception { - if (localBroker == null) { - localBroker = createFirstBroker(); - localBroker.start(); - localBroker.waitUntilStarted(); - } - } - - protected void stopLocalBroker() throws Exception { - if (localBroker != null) { - localBroker.stop(); - localBroker.waitUntilStopped(); - localBroker = null; - } - } - - protected void startForeignBroker() throws Exception { - if (foreignBroker == null) { - foreignBroker = createSecondBroker(); - foreignBroker.start(); - foreignBroker.waitUntilStarted(); - } - } - - protected void stopForeignBroker() throws Exception { - if (foreignBroker != null) { - foreignBroker.stop(); - foreignBroker.waitUntilStopped(); - foreignBroker = null; - } - } - - protected BrokerService createFirstBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("broker1"); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://localhost:61616"); - - return broker; - } - - protected BrokerService createSecondBroker() throws Exception { - - BrokerService broker = new BrokerService(); - broker.setBrokerName("broker2"); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://localhost:61617"); - - return broker; - } - - protected ActiveMQConnectionFactory createLocalConnectionFactory() { - return new ActiveMQConnectionFactory("tcp://localhost:61616"); - } - - protected ActiveMQConnectionFactory createForeignConnectionFactory() { - return new ActiveMQConnectionFactory("tcp://localhost:61617"); - } - - protected void sendMessageToForeignBroker(String text) throws JMSException { - Connection connection = null; - try { - connection = localConnectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(outbound); - TextMessage message = session.createTextMessage(); - message.setText(text); - producer.send(message); - } finally { - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } - - protected void sendMessageToLocalBroker(String text) throws JMSException { - Connection connection = null; - try { - connection = foreignConnectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(inbound); - TextMessage message = session.createTextMessage(); - message.setText(text); - producer.send(message); - } finally { - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } - - protected MessageConsumer createConsumerForLocalBroker() throws JMSException { - Connection connection = localConnectionFactory.createConnection(); - connections.add(connection); - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - return session.createConsumer(inbound); - } - - protected MessageConsumer createConsumerForForeignBroker() throws JMSException { - Connection connection = foreignConnectionFactory.createConnection(); - connections.add(connection); - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - return session.createConsumer(outbound); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeXBeanTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeXBeanTest.java deleted file mode 100644 index 72913ada0c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicBridgeXBeanTest.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.activemq.network.jms; - -import org.apache.xbean.spring.context.ClassPathXmlApplicationContext; -import org.springframework.context.support.AbstractApplicationContext; - -/** - * - * - */ -public class TopicBridgeXBeanTest extends TopicBridgeSpringTest { - - @Override - protected AbstractApplicationContext createApplicationContext() { - return new ClassPathXmlApplicationContext("org/apache/activemq/network/jms/topic-config.xml"); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicOutboundBridgeReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicOutboundBridgeReconnectTest.java deleted file mode 100644 index f7eadfaec0..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/TopicOutboundBridgeReconnectTest.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.activemq.network.jms; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.util.Wait; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -/** - * These test cases are used to verify that queue outbound bridge connections get - * re-established in all broker restart scenarios. This is possible when the - * outbound bridge is configured using the failover URI with a timeout. - */ -public class TopicOutboundBridgeReconnectTest { - - private BrokerService producerBroker; - private BrokerService consumerBroker; - private ActiveMQConnectionFactory producerConnectionFactory; - private ActiveMQConnectionFactory consumerConnectionFactory; - private Destination destination; - private final ArrayList connections = new ArrayList<>(); - - @Test - public void testMultipleProducerBrokerRestarts() throws Exception { - for (int i = 0; i < 10; i++) { - testWithProducerBrokerRestart(); - disposeConsumerConnections(); - } - } - - @Test - public void testWithoutRestartsConsumerFirst() throws Exception { - startConsumerBroker(); - startProducerBroker(); - - MessageConsumer consumer = createConsumer(); - - sendMessage("test123"); - sendMessage("test456"); - Message message = consumer.receive(2000); - assertNotNull(message); - assertEquals("test123", ((TextMessage) message).getText()); - - message = consumer.receive(5000); - assertNotNull(message); - assertEquals("test456", ((TextMessage) message).getText()); - - assertNull(consumer.receiveNoWait()); - } - - @Test - public void testWithoutRestartsProducerFirst() throws Exception { - startProducerBroker(); - sendMessage("test123"); - - startConsumerBroker(); - - // unless using a failover URI, the first attempt of this send will likely fail, so increase the timeout below - // to give the bridge time to recover - sendMessage("test456"); - - MessageConsumer consumer = createConsumer(); - Message message = consumer.receive(5000); - assertNotNull(message); - assertEquals("test123", ((TextMessage) message).getText()); - - message = consumer.receive(5000); - assertNotNull(message); - assertEquals("test456", ((TextMessage) message).getText()); - - assertNull(consumer.receiveNoWait()); - } - - @Test - public void testWithProducerBrokerRestart() throws Exception { - startProducerBroker(); - startConsumerBroker(); - - MessageConsumer consumer = createConsumer(); - - sendMessage("test123"); - Message message = consumer.receive(5000); - assertNotNull(message); - assertEquals("test123", ((TextMessage) message).getText()); - assertNull(consumer.receiveNoWait()); - - // Restart the first broker... - stopProducerBroker(); - startProducerBroker(); - - sendMessage("test123"); - message = consumer.receive(5000); - assertNotNull(message); - assertEquals("test123", ((TextMessage) message).getText()); - assertNull(consumer.receiveNoWait()); - } - - @Test - public void testWithConsumerBrokerRestart() throws Exception { - startProducerBroker(); - startConsumerBroker(); - - final MessageConsumer consumer1 = createConsumer(); - - sendMessage("test123"); - Message message = consumer1.receive(5000); - assertNotNull(message); - assertEquals("test123", ((TextMessage) message).getText()); - assertNull(consumer1.receiveNoWait()); - consumer1.close(); - - // Restart the first broker... - stopConsumerBroker(); - startConsumerBroker(); - - // unless using a failover URI, the first attempt of this send will likely fail, so increase the timeout below - // to give the bridge time to recover - sendMessage("test123"); - - final MessageConsumer consumer2 = createConsumer(); - assertTrue("Expected recover and delivery failed", Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - Message message = consumer2.receiveNoWait(); - if (message == null || !((TextMessage) message).getText().equals("test123")) { - return false; - } - return true; - } - })); - assertNull(consumer2.receiveNoWait()); - } - - @Test - public void testWithConsumerBrokerStartDelay() throws Exception { - startConsumerBroker(); - final MessageConsumer consumer = createConsumer(); - - TimeUnit.SECONDS.sleep(5); - - startProducerBroker(); - - sendMessage("test123"); - assertTrue("Expected recover and delivery failed", Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - Message message = consumer.receiveNoWait(); - if (message == null || !((TextMessage) message).getText().equals("test123")) { - return false; - } - return true; - } - })); - assertNull(consumer.receiveNoWait()); - } - - @Test - public void testWithProducerBrokerStartDelay() throws Exception { - startProducerBroker(); - - TimeUnit.SECONDS.sleep(5); - - startConsumerBroker(); - MessageConsumer consumer = createConsumer(); - - sendMessage("test123"); - Message message = consumer.receive(2000); - assertNotNull(message); - assertEquals("test123", ((TextMessage) message).getText()); - assertNull(consumer.receiveNoWait()); - } - - @Before - public void setUp() throws Exception { - producerConnectionFactory = createProducerConnectionFactory(); - consumerConnectionFactory = createConsumerConnectionFactory(); - destination = new ActiveMQTopic("RECONNECT.TEST.TOPIC"); - } - - @After - public void tearDown() throws Exception { - disposeConsumerConnections(); - try { - stopProducerBroker(); - } catch (Throwable e) { - } - try { - stopConsumerBroker(); - } catch (Throwable e) { - } - } - - protected void disposeConsumerConnections() { - for (Iterator iter = connections.iterator(); iter.hasNext(); ) { - Connection connection = iter.next(); - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } - - protected void startProducerBroker() throws Exception { - if (producerBroker == null) { - producerBroker = createFirstBroker(); - producerBroker.start(); - } - } - - protected void stopProducerBroker() throws Exception { - if (producerBroker != null) { - producerBroker.stop(); - producerBroker = null; - } - } - - protected void startConsumerBroker() throws Exception { - if (consumerBroker == null) { - consumerBroker = createSecondBroker(); - consumerBroker.start(); - } - } - - protected void stopConsumerBroker() throws Exception { - if (consumerBroker != null) { - consumerBroker.stop(); - consumerBroker = null; - } - } - - protected BrokerService createFirstBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("broker1"); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://localhost:61616"); - broker.addConnector("vm://broker1"); - - SimpleJmsTopicConnector jmsTopicConnector = new SimpleJmsTopicConnector(); - jmsTopicConnector.setOutboundTopicBridges(new OutboundTopicBridge[]{new OutboundTopicBridge("RECONNECT.TEST.TOPIC")}); - jmsTopicConnector.setOutboundTopicConnectionFactory(new ActiveMQConnectionFactory("tcp://localhost:61617")); - - broker.setJmsBridgeConnectors(new JmsConnector[]{jmsTopicConnector}); - - return broker; - } - - protected BrokerService createSecondBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("broker2"); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://localhost:61617"); - broker.addConnector("vm://broker2"); - - return broker; - } - - protected ActiveMQConnectionFactory createProducerConnectionFactory() { - return new ActiveMQConnectionFactory("vm://broker1"); - } - - protected ActiveMQConnectionFactory createConsumerConnectionFactory() { - return new ActiveMQConnectionFactory("vm://broker2"); - } - - protected void sendMessage(String text) throws JMSException { - Connection connection = null; - try { - connection = producerConnectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage(); - message.setText(text); - producer.send(message); - } finally { - try { - connection.close(); - } catch (Throwable ignore) { - } - } - } - - protected MessageConsumer createConsumer() throws JMSException { - Connection connection = consumerConnectionFactory.createConnection(); - connections.add(connection); - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - return session.createConsumer(destination); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/queue-config.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/queue-config.xml deleted file mode 100644 index a1bc29900e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/queue-config.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - - - - - - - - - - tcp://localhost:61666 - - - - - - - - - - - - - - - - - tcp://localhost:61234 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/queue-xbean.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/queue-xbean.xml deleted file mode 100644 index 017e89c6d0..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/queue-xbean.xml +++ /dev/null @@ -1,72 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/topic-config.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/topic-config.xml deleted file mode 100644 index 228274d311..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/topic-config.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - - - - - - - - - - tcp://localhost:61666 - - - - - - - - - - - - - - - - - tcp://localhost:61234 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/topic-spring.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/topic-spring.xml deleted file mode 100644 index fcb3ec5e2c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/jms/topic-spring.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - - - - - - - - - - tcp://localhost:61666 - - - - - - - - - - - - - - - - - tcp://localhost:61234 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/localBroker-plain.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/localBroker-plain.xml deleted file mode 100644 index f7db757965..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/localBroker-plain.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/localBroker.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/localBroker.xml deleted file mode 100644 index 5a176a920f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/localBroker.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/multicast/localBroker.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/multicast/localBroker.xml deleted file mode 100644 index fbdfa06a99..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/multicast/localBroker.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/multicast/remoteBroker.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/multicast/remoteBroker.xml deleted file mode 100644 index c56e093df5..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/multicast/remoteBroker.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/reconnect-broker1.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/reconnect-broker1.xml deleted file mode 100644 index e7c124ea74..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/reconnect-broker1.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/reconnect-broker2.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/reconnect-broker2.xml deleted file mode 100644 index 24604d9df5..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/reconnect-broker2.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/remoteBroker.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/remoteBroker.xml deleted file mode 100644 index fadba99168..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/remoteBroker.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/ssh-reconnect-broker1.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/ssh-reconnect-broker1.xml deleted file mode 100644 index 592fd5252b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/ssh-reconnect-broker1.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/ssh-reconnect-broker2.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/ssh-reconnect-broker2.xml deleted file mode 100644 index d3d52ddf12..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/network/ssh-reconnect-broker2.xml +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/ConnectionChurnTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/ConnectionChurnTest.java deleted file mode 100644 index f2a7afb6e0..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/ConnectionChurnTest.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.activemq.perf; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.JMSException; -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class ConnectionChurnTest extends TestCase { - - protected static final int CONNECTION_COUNT = 200; - private static final Logger LOG = LoggerFactory.getLogger(ConnectionChurnTest.class); - protected BrokerService broker; - protected String bindAddress = ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL + "?transport.closeAsync=false"; - protected int topicCount; - - public void testPerformance() throws Exception { - ConnectionFactory factory = createConnectionFactory(); - List list = new ArrayList<>(); - for (int i = 0; i < CONNECTION_COUNT; i++) { - Connection connection = factory.createConnection(); - connection.start(); - list.add(connection); - LOG.info("Created " + i); - if (i % 100 == 0) { - closeConnections(list); - } - } - closeConnections(list); - } - - protected void closeConnections(List list) throws JMSException { - for (Connection c : list) { - c.close(); - } - for (TransportConnector tc : broker.getTransportConnectors()) { - System.out.println(tc.getConnections().size()); - } - list.clear(); - } - - @Override - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(); - } - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - if (broker != null) { - broker.stop(); - } - } - - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL); - return cf; - } - - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - configureBroker(answer); - answer.start(); - return answer; - } - - protected void configureBroker(BrokerService answer) throws Exception { - answer.setPersistent(false); - answer.addConnector(bindAddress); - answer.setDeleteAllMessagesOnStartup(true); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/InactiveDurableTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/InactiveDurableTopicTest.java deleted file mode 100644 index f3b21be7d7..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/InactiveDurableTopicTest.java +++ /dev/null @@ -1,191 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.perf; - -import javax.jms.Connection; -import javax.jms.JMSException; -import javax.jms.MapMessage; -import javax.jms.Message; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.Topic; -import javax.jms.TopicSubscriber; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class InactiveDurableTopicTest extends TestCase { - - private static final transient Logger LOG = LoggerFactory.getLogger(InactiveDurableTopicTest.class); - - private static final int MESSAGE_COUNT = 2000; - private static final String DEFAULT_PASSWORD = ""; - private static final String USERNAME = "testuser"; - private static final String CLIENTID = "mytestclient"; - private static final String TOPIC_NAME = "testevent"; - private static final String SUBID = "subscription1"; - private static final int DELIVERY_MODE = javax.jms.DeliveryMode.PERSISTENT; - private static final int DELIVERY_PRIORITY = javax.jms.Message.DEFAULT_PRIORITY; - private Connection connection; - private MessageProducer publisher; - private TopicSubscriber subscriber; - private Topic topic; - private Session session; - private ActiveMQConnectionFactory connectionFactory; - private BrokerService broker; - - @Override - protected void setUp() throws Exception { - super.setUp(); - broker = new BrokerService(); - - //broker.setPersistenceAdapter(new KahaPersistenceAdapter()); - /* - * JournalPersistenceAdapterFactory factory = new - * JournalPersistenceAdapterFactory(); - * factory.setDataDirectoryFile(broker.getDataDirectory()); - * factory.setTaskRunnerFactory(broker.getTaskRunnerFactory()); - * factory.setUseJournal(false); broker.setPersistenceFactory(factory); - */ - broker.addConnector(ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL); - broker.start(); - connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_BROKER_URL); - /* - * Doesn't matter if you enable or disable these, so just leaving them - * out for this test case connectionFactory.setAlwaysSessionAsync(true); - * connectionFactory.setAsyncDispatch(true); - */ - connectionFactory.setUseAsyncSend(true); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - broker.stop(); - } - - public void test1CreateSubscription() throws Exception { - try { - /* - * Step 1 - Establish a connection with a client id and create a - * durable subscription - */ - connection = connectionFactory.createConnection(USERNAME, DEFAULT_PASSWORD); - assertNotNull(connection); - connection.setClientID(CLIENTID); - connection.start(); - session = connection.createSession(false, javax.jms.Session.CLIENT_ACKNOWLEDGE); - assertNotNull(session); - topic = session.createTopic(TOPIC_NAME); - assertNotNull(topic); - subscriber = session.createDurableSubscriber(topic, SUBID, "", false); - assertNotNull(subscriber); - subscriber.close(); - session.close(); - connection.close(); - } catch (JMSException ex) { - try { - connection.close(); - } catch (Exception ignore) { - } - throw new AssertionFailedError("Create Subscription caught: " + ex); - } - } - - public void test2ProducerTestCase() { - /* - * Step 2 - Establish a connection without a client id and create a - * producer and start pumping messages. We will get hung - */ - try { - connection = connectionFactory.createConnection(USERNAME, DEFAULT_PASSWORD); - assertNotNull(connection); - session = connection.createSession(false, javax.jms.Session.CLIENT_ACKNOWLEDGE); - assertNotNull(session); - topic = session.createTopic(TOPIC_NAME); - assertNotNull(topic); - publisher = session.createProducer(topic); - assertNotNull(publisher); - MapMessage msg = session.createMapMessage(); - assertNotNull(msg); - msg.setString("key1", "value1"); - int loop; - for (loop = 0; loop < MESSAGE_COUNT; loop++) { - msg.setInt("key2", loop); - publisher.send(msg, DELIVERY_MODE, DELIVERY_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); - if (loop % 5000 == 0) { - LOG.info("Sent " + loop + " messages"); - } - } - assertEquals(loop, MESSAGE_COUNT); - publisher.close(); - session.close(); - connection.stop(); - connection.stop(); - } catch (JMSException ex) { - try { - connection.close(); - } catch (Exception ignore) { - } - throw new AssertionFailedError("Create Subscription caught: " + ex); - } - } - - public void test3CreateSubscription() throws Exception { - try { - /* - * Step 1 - Establish a connection with a client id and create a - * durable subscription - */ - connection = connectionFactory.createConnection(USERNAME, DEFAULT_PASSWORD); - assertNotNull(connection); - connection.setClientID(CLIENTID); - connection.start(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - assertNotNull(session); - topic = session.createTopic(TOPIC_NAME); - assertNotNull(topic); - subscriber = session.createDurableSubscriber(topic, SUBID, "", false); - assertNotNull(subscriber); - int loop; - for (loop = 0; loop < MESSAGE_COUNT; loop++) { - subscriber.receive(); - if (loop % 500 == 0) { - LOG.debug("Received " + loop + " messages"); - } - } - assertEquals(loop, MESSAGE_COUNT); - subscriber.close(); - session.close(); - connection.close(); - } catch (JMSException ex) { - try { - connection.close(); - } catch (Exception ignore) { - } - throw new AssertionFailedError("Create Subscription caught: " + ex); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/InactiveQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/InactiveQueueTest.java deleted file mode 100644 index 52834dcd7a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/InactiveQueueTest.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.activemq.perf; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.MapMessage; -import javax.jms.Message; -import javax.jms.MessageProducer; -import javax.jms.Session; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class InactiveQueueTest extends TestCase { - - private static final transient Logger LOG = LoggerFactory.getLogger(InactiveQueueTest.class); - - private static final int MESSAGE_COUNT = 0; - private static final String DEFAULT_PASSWORD = ""; - private static final String USERNAME = "testuser"; - private static final String QUEUE_NAME = "testevent"; - private static final int DELIVERY_MODE = javax.jms.DeliveryMode.PERSISTENT; - private static final int DELIVERY_PRIORITY = javax.jms.Message.DEFAULT_PRIORITY; - - ActiveMQConnectionFactory connectionFactory; - BrokerService broker; - - private Connection connection; - private MessageProducer publisher; - private Destination destination; - private Session session; - - @Override - protected void setUp() throws Exception { - super.setUp(); - broker = new BrokerService(); - - // broker.setPersistenceAdapter(new KahaPersistenceAdapter(new File - // ("TEST_STUFD"))); - /* - * JournalPersistenceAdapterFactory factory = new - * JournalPersistenceAdapterFactory(); - * factory.setDataDirectoryFile(broker.getDataDirectory()); - * factory.setTaskRunnerFactory(broker.getTaskRunnerFactory()); - * factory.setUseJournal(false); broker.setPersistenceFactory(factory); - */ - broker.addConnector(ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL); - broker.start(); - connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_BROKER_URL); - /* - * Doesn't matter if you enable or disable these, so just leaving them - * out for this test case connectionFactory.setAlwaysSessionAsync(true); - * connectionFactory.setAsyncDispatch(true); - */ - connectionFactory.setUseAsyncSend(true); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - broker.stop(); - } - - public void testNoSubscribers() throws Exception { - connection = connectionFactory.createConnection(USERNAME, DEFAULT_PASSWORD); - assertNotNull(connection); - connection.start(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - assertNotNull(session); - destination = session.createQueue(QUEUE_NAME); - assertNotNull(destination); - publisher = session.createProducer(destination); - assertNotNull(publisher); - MapMessage msg = session.createMapMessage(); - assertNotNull(msg); - msg.setString("key1", "value1"); - int loop; - for (loop = 0; loop < MESSAGE_COUNT; loop++) { - msg.setInt("key2", loop); - publisher.send(msg, DELIVERY_MODE, DELIVERY_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); - if (loop % 500 == 0) { - LOG.debug("Sent " + loop + " messages"); - } - } - Thread.sleep(1000000); - assertEquals(loop, MESSAGE_COUNT); - publisher.close(); - session.close(); - connection.stop(); - connection.stop(); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBDurableTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBDurableTopicTest.java deleted file mode 100644 index cd84183a64..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBDurableTopicTest.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.activemq.perf; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; - -/** - * - */ -public class KahaDBDurableTopicTest extends SimpleDurableTopicTest { - - @Override - protected void setUp() throws Exception { - //this.initialConsumerDelay = 10 * 1000; - super.setUp(); - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory(String uri) throws Exception { - ActiveMQConnectionFactory result = new ActiveMQConnectionFactory(uri); - //result.setDispatchAsync(false); - return result; - } - - @Override - protected void configureBroker(BrokerService answer, String uri) throws Exception { - //AMQPersistenceAdapterFactory persistenceFactory = new AMQPersistenceAdapterFactory(); - //persistenceFactory.setMaxFileLength(1024*16); - //persistenceFactory.setPersistentIndex(true); - //persistenceFactory.setCleanupInterval(10000); - //answer.setPersistenceFactory(persistenceFactory); - answer.setDeleteAllMessagesOnStartup(true); - answer.addConnector(uri); - answer.setUseShutdownHook(false); - answer.setEnableStatistics(false); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBDurableTransactedTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBDurableTransactedTopicTest.java deleted file mode 100644 index 792e0ee92f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBDurableTransactedTopicTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.perf; - -import javax.jms.ConnectionFactory; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; - -/** - * - */ -public class KahaDBDurableTransactedTopicTest extends KahaDBDurableTopicTest { - - @Override - protected void setUp() throws Exception { - //this.initialConsumerDelay = 10 * 1000; - super.setUp(); - } - - @Override - protected PerfProducer createProducer(ConnectionFactory fac, - Destination dest, - int number, - byte[] payload) throws JMSException { - PerfProducer result = new PerfProducer(fac, dest, payload, true); - result.setDeliveryMode(DeliveryMode.PERSISTENT); - return result; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBQueueTest.java deleted file mode 100644 index 11a3ef5a54..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaDBQueueTest.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.activemq.perf; - -import java.io.File; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; - -/** - * - */ -public class KahaDBQueueTest extends SimpleQueueTest { - - @Override - protected void setUp() throws Exception { - this.numberOfDestinations = 25; - this.numberofProducers = 1; - super.setUp(); - } - - @Override - protected void configureBroker(BrokerService answer, String uri) throws Exception { - - File dataFileDir = new File("target/test-amq-data/perfTest/kahadb"); - File archiveDir = new File(dataFileDir, "archive"); - KahaDBPersistenceAdapter kaha = new KahaDBPersistenceAdapter(); - kaha.setDirectory(dataFileDir); - kaha.setDirectoryArchive(archiveDir); - kaha.setArchiveDataLogs(false); - - // The setEnableJournalDiskSyncs(false) setting is a little dangerous right now, as I have not verified - // what happens if the index is updated but a journal update is lost. - // Index is going to be in consistent, but can it be repaired? - kaha.setEnableJournalDiskSyncs(true); - // Using a bigger journal file size makes he take fewer spikes as it is not switching files as often. - //kaha.setJournalMaxFileLength(1024*1024*100); - - // small batch means more frequent and smaller writes - //kaha.setIndexWriteBatchSize(100); - // do the index write in a separate thread - kaha.setEnableIndexWriteAsync(true); - kaha.setIndexCacheSize(10000); - - answer.setPersistenceAdapter(kaha); - answer.addConnector(uri); - answer.setDeleteAllMessagesOnStartup(true); - - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaQueueTest.java deleted file mode 100644 index 194a0bcaad..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/KahaQueueTest.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.activemq.perf; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.xbean.BrokerFactoryBean; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; - -/** - * - */ -public class KahaQueueTest extends SimpleQueueTest { - - final static String config = "org/apache/activemq/perf/kahadbBroker.xml"; - - @Override - protected BrokerService createBroker(String uri) throws Exception { - Resource resource = new ClassPathResource(config); - BrokerFactoryBean brokerFactory = new BrokerFactoryBean(resource); - resource = new ClassPathResource(config); - brokerFactory = new BrokerFactoryBean(resource); - brokerFactory.afterPropertiesSet(); - return brokerFactory.getBroker(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/LevelDBDurableTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/LevelDBDurableTopicTest.java deleted file mode 100644 index 254cb865ae..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/LevelDBDurableTopicTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * revision 946600 * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.perf; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.leveldb.LevelDBStore; - -/** - * - */ -public class LevelDBDurableTopicTest extends SimpleDurableTopicTest { - - /* - * protected BrokerService createBroker() throws Exception{ Resource - * resource=new ClassPathResource( - * "org/apache/activemq/perf/kahaBroker.xml"); BrokerFactoryBean factory=new - * BrokerFactoryBean(resource); factory.afterPropertiesSet(); BrokerService - * result=factory.getBroker(); result.start(); return result; } - */ - - @Override - protected void configureBroker(BrokerService answer, String uri) throws Exception { - LevelDBStore store = new LevelDBStore(); - answer.setPersistenceAdapter(store); - answer.setDeleteAllMessagesOnStartup(true); - answer.addConnector(uri); - - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/LevelDBStoreQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/LevelDBStoreQueueTest.java deleted file mode 100644 index d9f772dbe3..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/LevelDBStoreQueueTest.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.activemq.perf; - -import java.io.File; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.leveldb.LevelDBStore; - -/** - * - */ -public class LevelDBStoreQueueTest extends SimpleQueueTest { - - @Override - protected void configureBroker(BrokerService answer, String uri) throws Exception { - - File dataFileDir = new File("target/test-amq-data/perfTest/amq"); - - LevelDBStore adaptor = new LevelDBStore(); - adaptor.setDirectory(dataFileDir); - - answer.setPersistenceAdapter(adaptor); - answer.addConnector(uri); - answer.setDeleteAllMessagesOnStartup(true); - - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/MemoryAllocationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/MemoryAllocationTest.java deleted file mode 100644 index 8a7a27356c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/MemoryAllocationTest.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.activemq.perf; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TemporaryQueue; -import javax.jms.TemporaryTopic; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class MemoryAllocationTest extends TestCase { - - protected static final int MESSAGE_COUNT = 2000; - private static final Logger LOG = LoggerFactory.getLogger(MemoryAllocationTest.class); - - protected BrokerService broker; - protected String bindAddress = "vm://localhost"; - protected int topicCount; - - public void testPerformance() throws Exception { - ConnectionFactory factory = createConnectionFactory(); - Connection connection = factory.createConnection(); - for (int i = 0; i < MESSAGE_COUNT; i++) { - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination dest = session.createTemporaryTopic(); - session.createConsumer(dest); - MessageProducer mp = session.createProducer(dest); - Message msg = session.createTextMessage("test" + i); - mp.send(msg); - session.close(); - releaseDestination(dest); - if (i % 500 == 0) { - LOG.info("Iterator " + i); - } - } - connection.close(); - } - - protected Destination getDestination(Session session) throws JMSException { - String topicName = getClass().getName() + "." + topicCount++; - return session.createTopic(topicName); - } - - protected void releaseDestination(Destination dest) throws JMSException { - if (dest instanceof TemporaryTopic) { - TemporaryTopic tt = (TemporaryTopic) dest; - tt.delete(); - } else if (dest instanceof TemporaryQueue) { - TemporaryQueue tq = (TemporaryQueue) dest; - tq.delete(); - } - } - - @Override - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(); - } - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - - if (broker != null) { - broker.stop(); - } - } - - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(bindAddress); - return cf; - } - - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - configureBroker(answer); - answer.start(); - return answer; - } - - protected void configureBroker(BrokerService answer) throws Exception { - answer.setPersistent(false); - answer.addConnector(bindAddress); - answer.setDeleteAllMessagesOnStartup(true); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/NetworkedSyncTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/NetworkedSyncTest.java deleted file mode 100644 index 129d5a850b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/NetworkedSyncTest.java +++ /dev/null @@ -1,305 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.perf; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.jms.Topic; - -import junit.framework.TestCase; - -import junit.textui.TestRunner; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.xbean.BrokerFactoryBean; -import org.apache.xbean.spring.context.ClassPathXmlApplicationContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.ClassPathResource; - -public class NetworkedSyncTest extends TestCase { - - public static final int MESSAGE_COUNT = 10000; //100000; - public final static String config = "org/apache/activemq/perf/networkSync.xml"; - public final static String broker1URL = "tcp://localhost:61616"; - public final static String broker2URL = "tcp://localhost:62616"; - private final String networkConnectorURL = "static://(" + broker2URL + ")"; - private static final Logger LOG = LoggerFactory.getLogger(NetworkedSyncTest.class); - BrokerService broker1 = null; - BrokerService broker2 = null; - NetworkConnector connector = null; - - /** - * @param name - */ - public NetworkedSyncTest(String name) { - super(name); - LOG.info("Testcase started."); - } - - public static void main(String args[]) { - TestRunner.run(NetworkedSyncTest.class); - } - - /** - * @throws java.lang.Exception - */ - @Override - protected void setUp() throws Exception { - LOG.info("setUp() called."); - ClassPathXmlApplicationContext context1 = null; - BrokerFactoryBean brokerFactory = new BrokerFactoryBean(new ClassPathResource(config)); - assertNotNull(brokerFactory); - - /* start up first broker instance */ - try { - // resolve broker1 - Thread.currentThread().setContextClassLoader(NetworkedSyncTest.class.getClassLoader()); - context1 = new ClassPathXmlApplicationContext(config); - broker1 = (BrokerService) context1.getBean("broker1"); - - // start the broker - if (!broker1.isStarted()) { - LOG.info("Broker broker1 not yet started. Kicking it off now."); - broker1.start(); - } else { - LOG.info("Broker broker1 already started. Not kicking it off a second time."); - broker1.waitUntilStopped(); - } - } catch (Exception e) { - LOG.error("Error: " + e.getMessage()); - throw e; - // brokerService.stop(); - } - - /* start up second broker instance */ - try { - Thread.currentThread().setContextClassLoader(NetworkedSyncTest.class.getClassLoader()); - context1 = new ClassPathXmlApplicationContext(config); - broker2 = (BrokerService) context1.getBean("broker2"); - - // start the broker - if (!broker2.isStarted()) { - LOG.info("Broker broker2 not yet started. Kicking it off now."); - broker2.start(); - } else { - LOG.info("Broker broker2 already started. Not kicking it off a second time."); - broker2.waitUntilStopped(); - } - } catch (Exception e) { - LOG.error("Error: " + e.getMessage()); - throw e; - } - - // setup network connector from broker1 to broker2 - connector = broker1.addNetworkConnector(networkConnectorURL); - connector.setBrokerName(broker1.getBrokerName()); - connector.setDuplex(true); - connector.start(); - LOG.info("Network connector created."); - } - - /** - * @throws java.lang.Exception - */ - @Override - protected void tearDown() throws Exception { - - LOG.info("tearDown() called."); - - if (broker1 != null && broker1.isStarted()) { - LOG.info("Broker1 still running, stopping it now."); - broker1.stop(); - } else { - LOG.info("Broker1 not running, nothing to shutdown."); - } - if (broker2 != null && broker2.isStarted()) { - LOG.info("Broker2 still running, stopping it now."); - broker2.stop(); - } else { - LOG.info("Broker2 not running, nothing to shutdown."); - } - - } - - public void testMessageExchange() throws Exception { - LOG.info("testMessageExchange() called."); - - long start = System.currentTimeMillis(); - - // create producer and consumer threads - Thread producer = new Thread(new Producer()); - Thread consumer = new Thread(new Consumer()); - // start threads - consumer.start(); - Thread.sleep(2000); - producer.start(); - - // wait for threads to finish - producer.join(); - consumer.join(); - long end = System.currentTimeMillis(); - - System.out.println("Duration: " + (end - start)); - } -} - -/** - * Message producer running as a separate thread, connecting to broker1 - * - * @author tmielke - */ -class Producer implements Runnable { - - private static final Logger LOG = LoggerFactory.getLogger(Producer.class); - - /** - * connect to broker and constantly send messages - */ - @Override - public void run() { - - Connection connection = null; - Session session = null; - MessageProducer producer = null; - - try { - ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory(NetworkedSyncTest.broker1URL); - connection = amq.createConnection(); - - connection.setExceptionListener(new javax.jms.ExceptionListener() { - @Override - public void onException(javax.jms.JMSException e) { - e.printStackTrace(); - } - }); - - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic destination = session.createTopic("TEST.FOO"); - - producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - - long counter = 0; - - // Create and send message - for (int i = 0; i < NetworkedSyncTest.MESSAGE_COUNT; i++) { - - String text = "Hello world! From: " + Thread.currentThread().getName() + " : " + this.hashCode() + ":" + counter; - TextMessage message = session.createTextMessage(text); - producer.send(message); - counter++; - - if ((counter % 1000) == 0) - LOG.info("sent " + counter + " messages"); - - } - } catch (Exception ex) { - LOG.error(ex.toString()); - return; - } finally { - try { - if (producer != null) - producer.close(); - if (session != null) - session.close(); - if (connection != null) - connection.close(); - } catch (Exception e) { - LOG.error("Problem closing down JMS objects: " + e); - } - } - } -} - -/* - * * Message consumer running as a separate thread, connecting to broker2 - * @author tmielke - * - */ -class Consumer implements Runnable { - - private static final Logger LOG = LoggerFactory.getLogger(Consumer.class); - - /** - * connect to broker and receive messages - */ - @Override - public void run() { - Connection connection = null; - Session session = null; - MessageConsumer consumer = null; - - try { - ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory(NetworkedSyncTest.broker2URL); - connection = amq.createConnection(); - // need to set clientID when using durable subscription. - connection.setClientID("tmielke"); - - connection.setExceptionListener(new javax.jms.ExceptionListener() { - @Override - public void onException(javax.jms.JMSException e) { - e.printStackTrace(); - } - }); - - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createTopic("TEST.FOO"); - consumer = session.createDurableSubscriber((Topic) destination, "tmielke"); - - long counter = 0; - // Wait for a message - for (int i = 0; i < NetworkedSyncTest.MESSAGE_COUNT; i++) { - Message message2 = consumer.receive(); - if (message2 instanceof TextMessage) { - TextMessage textMessage = (TextMessage) message2; - textMessage.getText(); - // logger.info("Received: " + text); - } else { - LOG.error("Received message of unsupported type. Expecting TextMessage. " + message2); - } - counter++; - if ((counter % 1000) == 0) - LOG.info("received " + counter + " messages"); - - } - } catch (Exception e) { - LOG.error("Error in Consumer: " + e); - return; - } finally { - try { - if (consumer != null) - consumer.close(); - if (session != null) - session.close(); - if (connection != null) - connection.close(); - } catch (Exception ex) { - LOG.error("Error closing down JMS objects: " + ex); - } - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/NumberOfDestinationsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/NumberOfDestinationsTest.java deleted file mode 100644 index 632ec5e2e2..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/NumberOfDestinationsTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.perf; - -/** - * A NumberOfDestinationsTest - * - */ - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.io.File; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class NumberOfDestinationsTest extends TestCase { - - protected static final int MESSAGE_COUNT = 1; - protected static final int NUMBER_OF_DESTINATIONS = 100000; - private static final Logger LOG = LoggerFactory.getLogger(NumberOfDestinationsTest.class); - protected BrokerService broker; - protected String bindAddress = "vm://localhost"; - protected int destinationCount; - - public void testDestinations() throws Exception { - ConnectionFactory factory = createConnectionFactory(); - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer mp = session.createProducer(null); - for (int j = 0; j < NUMBER_OF_DESTINATIONS; j++) { - Destination dest = getDestination(session); - - for (int i = 0; i < MESSAGE_COUNT; i++) { - Message msg = session.createTextMessage("test" + i); - mp.send(dest, msg); - - } - if (j % 500 == 0) { - LOG.info("Iterator " + j); - } - } - - connection.close(); - } - - protected Destination getDestination(Session session) throws JMSException { - String topicName = getClass().getName() + "." + destinationCount++; - return session.createTopic(topicName); - } - - @Override - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(); - } - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - if (broker != null) { - broker.stop(); - } - } - - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(bindAddress); - return cf; - } - - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - configureBroker(answer); - answer.start(); - return answer; - } - - protected void configureBroker(BrokerService answer) throws Exception { - File dataFileDir = new File("target/test-amq-data/perfTest/kahadb"); - - KahaDBPersistenceAdapter kaha = new KahaDBPersistenceAdapter(); - kaha.setDirectory(dataFileDir); - //answer.setUseJmx(false); - - // The setEnableJournalDiskSyncs(false) setting is a little dangerous right now, as I have not verified - // what happens if the index is updated but a journal update is lost. - // Index is going to be in consistent, but can it be repaired? - //kaha.setEnableJournalDiskSyncs(false); - // Using a bigger journal file size makes he take fewer spikes as it is not switching files as often. - //kaha.setJournalMaxFileLength(1024*100); - - // small batch means more frequent and smaller writes - //kaha.setIndexWriteBatchSize(100); - // do the index write in a separate thread - //kaha.setEnableIndexWriteAsync(true); - - answer.setPersistenceAdapter(kaha); - answer.setAdvisorySupport(false); - answer.setEnableStatistics(false); - answer.addConnector(bindAddress); - answer.setDeleteAllMessagesOnStartup(true); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfConsumer.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfConsumer.java deleted file mode 100644 index 38afaadfcb..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfConsumer.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.activemq.perf; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.Session; -import javax.jms.Topic; - -import org.apache.activemq.ActiveMQMessageAudit; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class PerfConsumer implements MessageListener { - - private static final Logger LOG = LoggerFactory.getLogger(PerfConsumer.class); - protected Connection connection; - protected MessageConsumer consumer; - protected long sleepDuration; - protected long initialDelay; - protected boolean enableAudit = false; - protected ActiveMQMessageAudit audit = new ActiveMQMessageAudit(16 * 1024, 20); - protected boolean firstMessage = true; - protected String lastMsgId; - - protected PerfRate rate = new PerfRate(); - - public PerfConsumer(ConnectionFactory fac, Destination dest, String consumerName) throws JMSException { - connection = fac.createConnection(); - connection.setClientID(consumerName); - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - if (dest instanceof Topic && consumerName != null && consumerName.length() > 0) { - consumer = s.createDurableSubscriber((Topic) dest, consumerName); - } else { - consumer = s.createConsumer(dest); - } - consumer.setMessageListener(this); - } - - public PerfConsumer(ConnectionFactory fac, Destination dest) throws JMSException { - this(fac, dest, null); - } - - public void start() throws JMSException { - connection.start(); - rate.reset(); - } - - public void stop() throws JMSException { - connection.stop(); - } - - public void shutDown() throws JMSException { - connection.close(); - } - - public PerfRate getRate() { - return rate; - } - - @Override - public void onMessage(Message msg) { - if (firstMessage) { - firstMessage = false; - if (getInitialDelay() > 0) { - try { - Thread.sleep(getInitialDelay()); - } catch (InterruptedException e) { - } - } - } - rate.increment(); - try { - if (enableAudit && !this.audit.isInOrder(msg.getJMSMessageID())) { - LOG.error("Message out of order!!" + msg.getJMSMessageID() + " LAST = " + lastMsgId); - } - if (enableAudit && this.audit.isDuplicate(msg)) { - LOG.error("Duplicate Message!" + msg); - } - lastMsgId = msg.getJMSMessageID(); - } catch (JMSException e1) { - e1.printStackTrace(); - } - try { - if (sleepDuration != 0) { - Thread.sleep(sleepDuration); - } - } catch (InterruptedException e) { - } - } - - public synchronized long getSleepDuration() { - return sleepDuration; - } - - public synchronized void setSleepDuration(long sleepDuration) { - this.sleepDuration = sleepDuration; - } - - public boolean isEnableAudit() { - return enableAudit; - } - - public void setEnableAudit(boolean doAudit) { - this.enableAudit = doAudit; - } - - /** - * @return the initialDelay - */ - public long getInitialDelay() { - return initialDelay; - } - - /** - * @param initialDelay the initialDelay to set - */ - public void setInitialDelay(long initialDelay) { - this.initialDelay = initialDelay; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfProducer.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfProducer.java deleted file mode 100644 index fec7b6da48..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfProducer.java +++ /dev/null @@ -1,134 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.perf; - -import javax.jms.BytesMessage; -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * - */ -public class PerfProducer implements Runnable { - - protected Connection connection; - protected MessageProducer producer; - protected PerfRate rate = new PerfRate(); - private final byte[] payload; - private Session session; - private final CountDownLatch stopped = new CountDownLatch(1); - private boolean running; - private final boolean transacted; - private int sleep = 0; - - public PerfProducer(ConnectionFactory fac, Destination dest, byte[] payload) throws JMSException { - this(fac, dest, payload, false); - } - - public PerfProducer(ConnectionFactory fac, - Destination dest, - byte[] payload, - boolean transacted) throws JMSException { - connection = fac.createConnection(); - this.transacted = transacted; - if (transacted) { - session = connection.createSession(true, Session.SESSION_TRANSACTED); - } else { - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } - producer = session.createProducer(dest); - this.payload = payload; - - } - - public void setDeliveryMode(int mode) throws JMSException { - producer.setDeliveryMode(mode); - } - - public void setTimeToLive(int ttl) throws JMSException { - producer.setTimeToLive(ttl); - } - - public void shutDown() throws JMSException { - connection.close(); - } - - public PerfRate getRate() { - return rate; - } - - public synchronized void start() throws JMSException { - if (!running) { - rate.reset(); - running = true; - connection.start(); - Thread t = new Thread(this); - t.setName("Producer"); - t.start(); - } - } - - public void stop() throws JMSException, InterruptedException { - synchronized (this) { - running = false; - } - stopped.await(1, TimeUnit.SECONDS); - connection.stop(); - } - - public synchronized boolean isRunning() { - return running; - } - - @Override - public void run() { - try { - while (isRunning()) { - BytesMessage msg; - msg = session.createBytesMessage(); - msg.writeBytes(payload); - producer.send(msg); - if (this.transacted) { - this.session.commit(); - } - rate.increment(); - if (sleep > 0) { - Thread.sleep(sleep); - } - } - } catch (Throwable e) { - e.printStackTrace(); - } finally { - stopped.countDown(); - } - } - - public int getSleep() { - return sleep; - } - - public void setSleep(int sleep) { - this.sleep = sleep; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfRate.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfRate.java deleted file mode 100644 index 7033c7465c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/PerfRate.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.activemq.perf; - -/** - * - */ -public class PerfRate { - - protected int totalCount; - protected int count; - protected long startTime = System.currentTimeMillis(); - - /** - * @return Returns the count. - */ - public int getCount() { - return totalCount; - } - - public synchronized void increment() { - totalCount++; - count++; - } - - public int getRate() { - long endTime = System.currentTimeMillis(); - long totalTime = endTime - startTime; - int result = (int) ((count * 1000) / totalTime); - return result; - } - - /** - * Resets the rate sampling. - */ - public synchronized PerfRate cloneAndReset() { - PerfRate rc = new PerfRate(); - rc.totalCount = totalCount; - rc.count = count; - rc.startTime = startTime; - count = 0; - startTime = System.currentTimeMillis(); - return rc; - } - - /** - * Resets the rate sampling. - */ - public void reset() { - count = 0; - startTime = System.currentTimeMillis(); - } - - /** - * @return Returns the totalCount. - */ - public int getTotalCount() { - return totalCount; - } - - /** - * @param totalCount The totalCount to set. - */ - public void setTotalCount(int totalCount) { - this.totalCount = totalCount; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/QueueConnectionMemoryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/QueueConnectionMemoryTest.java deleted file mode 100644 index 87164af1b8..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/QueueConnectionMemoryTest.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.activemq.perf; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Session; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.leveldb.LevelDBStore; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class QueueConnectionMemoryTest extends SimpleQueueTest { - - private static final transient Logger LOG = LoggerFactory.getLogger(QueueConnectionMemoryTest.class); - - @Override - protected void setUp() throws Exception { - } - - @Override - protected void tearDown() throws Exception { - - } - - @Override - protected Destination createDestination(Session s, String destinationName) throws JMSException { - return s.createTemporaryQueue(); - } - - @Override - public void testPerformance() throws JMSException { - // just cancel super class test - } - - @Override - protected void configureBroker(BrokerService answer, String uri) throws Exception { - LevelDBStore adaptor = new LevelDBStore(); - answer.setPersistenceAdapter(adaptor); - answer.addConnector(uri); - answer.setDeleteAllMessagesOnStartup(true); - } - - public void testMemory() throws Exception { - if (broker == null) { - broker = createBroker(bindAddress); - } - factory = createConnectionFactory(bindAddress); - Connection con = factory.createConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - createDestination(session, destinationName); - con.close(); - for (int i = 0; i < 3; i++) { - Connection connection = factory.createConnection(); - connection.start(); - Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination dest = s.createTemporaryQueue(); - s.createConsumer(dest); - LOG.debug("Created connnection: " + i); - Thread.sleep(1000); - } - - Thread.sleep(Integer.MAX_VALUE); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/RunBroker.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/RunBroker.java deleted file mode 100644 index aa8f6fc558..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/RunBroker.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.activemq.perf; - -import java.io.File; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.util.IOHelper; - -public class RunBroker { - - public static void main(String arg[]) { - - try { - KahaDBPersistenceAdapter kahaDB = new KahaDBPersistenceAdapter(); - File dataFileDir = new File("target/test-amq-data/perfTest/kahadb"); - IOHelper.deleteChildren(dataFileDir); - kahaDB.setDirectory(dataFileDir); - - // The setEnableJournalDiskSyncs(false) setting is a little - // dangerous right now, as I have not verified - // what happens if the index is updated but a journal update is - // lost. - // Index is going to be in consistent, but can it be repaired? - // kaha.setEnableJournalDiskSyncs(false); - // Using a bigger journal file size makes he take fewer spikes as it - // is not switching files as often. - // kaha.setJournalMaxFileLength(1024*1024*100); - - // small batch means more frequent and smaller writes - kahaDB.setIndexWriteBatchSize(1000); - kahaDB.setIndexCacheSize(10000); - - // do the index write in a separate thread - // kahaDB.setEnableIndexWriteAsync(true); - BrokerService broker = new BrokerService(); - broker.setUseJmx(false); - // broker.setPersistenceAdapter(adaptor); - broker.setPersistenceAdapter(kahaDB); - // broker.setPersistent(false); - broker.setDeleteAllMessagesOnStartup(true); - broker.addConnector("tcp://0.0.0.0:61616"); - broker.start(); - System.err.println("Running"); - Thread.sleep(Long.MAX_VALUE); - } catch (Throwable e) { - e.printStackTrace(); - } - - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleDurableTopicNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleDurableTopicNetworkTest.java deleted file mode 100644 index b5474a44a6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleDurableTopicNetworkTest.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.activemq.perf; - -import javax.jms.ConnectionFactory; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; - -public class SimpleDurableTopicNetworkTest extends SimpleNetworkTest { - - @Override - protected void setUp() throws Exception { - numberofProducers = 1; - numberOfConsumers = 1; - sampleCount = 1000; - playloadSize = 1024; - super.setUp(); - } - - @Override - protected PerfProducer createProducer(ConnectionFactory fac, - Destination dest, - int number, - byte payload[]) throws JMSException { - PerfProducer pp = new PerfProducer(fac, dest, payload); - pp.setDeliveryMode(DeliveryMode.PERSISTENT); - return pp; - } - - @Override - protected PerfConsumer createConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { - return new PerfConsumer(fac, dest, "subs:" + number); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleDurableTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleDurableTopicTest.java deleted file mode 100644 index 0af3e4680b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleDurableTopicTest.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.activemq.perf; - -import javax.jms.ConnectionFactory; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.leveldb.LevelDBStoreFactory; - -/** - * - */ -public class SimpleDurableTopicTest extends SimpleTopicTest { - - protected long initialConsumerDelay = 0; - - @Override - protected void setUp() throws Exception { - numberOfDestinations = 1; - numberOfConsumers = 1; - numberofProducers = Integer.parseInt(System.getProperty("SimpleDurableTopicTest.numberofProducers", "20"), 20); - sampleCount = Integer.parseInt(System.getProperty("SimpleDurableTopicTest.sampleCount", "1000"), 10); - playloadSize = 1024; - super.setUp(); - } - - @Override - protected void configureBroker(BrokerService answer, String uri) throws Exception { - LevelDBStoreFactory persistenceFactory = new LevelDBStoreFactory(); - answer.setPersistenceFactory(persistenceFactory); - //answer.setDeleteAllMessagesOnStartup(true); - answer.addConnector(uri); - answer.setUseShutdownHook(false); - } - - @Override - protected PerfProducer createProducer(ConnectionFactory fac, - Destination dest, - int number, - byte payload[]) throws JMSException { - PerfProducer pp = new PerfProducer(fac, dest, payload); - pp.setDeliveryMode(DeliveryMode.PERSISTENT); - return pp; - } - - @Override - protected PerfConsumer createConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { - PerfConsumer result = new PerfConsumer(fac, dest, "subs:" + number); - result.setInitialDelay(this.initialConsumerDelay); - return result; - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory(String uri) throws Exception { - ActiveMQConnectionFactory result = super.createConnectionFactory(uri); - //result.setSendAcksAsync(false); - return result; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNetworkTest.java deleted file mode 100644 index ec2e030c52..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNetworkTest.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.activemq.perf; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.Session; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ActiveMQPrefetchPolicy; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.network.NetworkConnector; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SimpleNetworkTest extends SimpleTopicTest { - - private static final Logger LOG = LoggerFactory.getLogger(SimpleNetworkTest.class); - protected String consumerBindAddress = "tcp://localhost:61616"; - protected String producerBindAddress = "tcp://localhost:61617"; - protected static final String CONSUMER_BROKER_NAME = "Consumer"; - protected static final String PRODUCER_BROKER_NAME = "Producer"; - protected BrokerService consumerBroker; - protected BrokerService producerBroker; - protected ActiveMQConnectionFactory consumerFactory; - protected ActiveMQConnectionFactory producerFactory; - - @Override - protected void setUp() throws Exception { - if (consumerBroker == null) { - consumerBroker = createConsumerBroker(consumerBindAddress); - } - if (producerBroker == null) { - producerBroker = createProducerBroker(producerBindAddress); - } - consumerFactory = createConnectionFactory(consumerBindAddress); - consumerFactory.setDispatchAsync(true); - ActiveMQPrefetchPolicy policy = new ActiveMQPrefetchPolicy(); - policy.setQueuePrefetch(100); - consumerFactory.setPrefetchPolicy(policy); - producerFactory = createConnectionFactory(producerBindAddress); - Connection con = consumerFactory.createConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - - producers = new PerfProducer[numberofProducers * numberOfDestinations]; - consumers = new PerfConsumer[numberOfConsumers * numberOfDestinations]; - - for (int k = 0; k < numberOfDestinations; k++) { - Destination destination = createDestination(session, destinationName + ":" + k); - LOG.info("Testing against destination: " + destination); - for (int i = 0; i < numberOfConsumers; i++) { - consumers[i] = createConsumer(consumerFactory, destination, i); - consumers[i].start(); - } - for (int i = 0; i < numberofProducers; i++) { - array = new byte[playloadSize]; - for (int j = i; j < array.length; j++) { - array[j] = (byte) j; - } - producers[i] = createProducer(producerFactory, destination, i, array); - producers[i].start(); - - } - } - con.close(); - } - - @Override - protected void tearDown() throws Exception { - for (int i = 0; i < numberOfConsumers; i++) { - consumers[i].shutDown(); - } - for (int i = 0; i < numberofProducers; i++) { - producers[i].shutDown(); - } - - if (producerBroker != null) { - producerBroker.stop(); - producerBroker = null; - } - if (consumerBroker != null) { - consumerBroker.stop(); - consumerBroker = null; - } - } - - protected BrokerService createConsumerBroker(String uri) throws Exception { - BrokerService answer = new BrokerService(); - configureConsumerBroker(answer, uri); - answer.start(); - return answer; - } - - protected void configureConsumerBroker(BrokerService answer, String uri) throws Exception { - configureBroker(answer); - answer.setPersistent(false); - answer.setBrokerName(CONSUMER_BROKER_NAME); - answer.setDeleteAllMessagesOnStartup(true); - answer.addConnector(uri); - answer.setUseShutdownHook(false); - } - - protected BrokerService createProducerBroker(String uri) throws Exception { - BrokerService answer = new BrokerService(); - configureProducerBroker(answer, uri); - answer.start(); - return answer; - } - - protected void configureProducerBroker(BrokerService answer, String uri) throws Exception { - configureBroker(answer); - answer.setBrokerName(PRODUCER_BROKER_NAME); - answer.setMonitorConnectionSplits(false); - //answer.setSplitSystemUsageForProducersConsumers(true); - answer.setPersistent(false); - answer.setDeleteAllMessagesOnStartup(true); - NetworkConnector connector = answer.addNetworkConnector("static://" + consumerBindAddress); - //connector.setNetworkTTL(3); - //connector.setDynamicOnly(true); - connector.setDuplex(true); - answer.addConnector(uri); - answer.setUseShutdownHook(false); - } - - protected void configureBroker(BrokerService service) throws Exception { - - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentQueueNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentQueueNetworkTest.java deleted file mode 100644 index e0c1afbe88..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentQueueNetworkTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.perf; - -import javax.jms.ConnectionFactory; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Session; -import java.util.ArrayList; -import java.util.List; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; - -public class SimpleNonPersistentQueueNetworkTest extends SimpleNetworkTest { - - @Override - protected void setUp() throws Exception { - numberOfDestinations = 20; - super.setUp(); - } - - @Override - protected PerfProducer createProducer(ConnectionFactory fac, - Destination dest, - int number, - byte[] payload) throws JMSException { - PerfProducer pp = new PerfProducer(fac, dest, payload); - pp.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - // pp.setTimeToLive(1000); - //pp.setSleep(1); - return pp; - } - - @Override - protected PerfConsumer createConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { - PerfConsumer consumer = new PerfConsumer(fac, dest); - boolean enableAudit = numberOfConsumers <= 1; - System.out.println("Enable Audit = " + enableAudit); - consumer.setEnableAudit(false); - return consumer; - } - - @Override - public void testPerformance() throws JMSException, InterruptedException { - //Thread.sleep(5000); - super.testPerformance(); - } - - @Override - protected Destination createDestination(Session s, String destinationName) throws JMSException { - return s.createQueue(destinationName); - } - - @Override - protected void configureBroker(BrokerService answer) throws Exception { - answer.setPersistent(false); - answer.setMonitorConnectionSplits(true); - final List policyEntries = new ArrayList<>(); - final PolicyEntry entry = new PolicyEntry(); - entry.setQueue(">"); - entry.setMemoryLimit(1024 * 1024 * 100); // Set to 1 MB - entry.setOptimizedDispatch(true); - entry.setProducerFlowControl(true); - entry.setMaxPageSize(10); - entry.setLazyDispatch(false); - policyEntries.add(entry); - - final PolicyMap policyMap = new PolicyMap(); - policyMap.setPolicyEntries(policyEntries); - answer.setDestinationPolicy(policyMap); - super.configureBroker(answer); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentQueueTest.java deleted file mode 100644 index 0c22d84812..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentQueueTest.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.activemq.perf; - -import javax.jms.ConnectionFactory; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; - -/** - * - */ -public class SimpleNonPersistentQueueTest extends SimpleQueueTest { - - @Override - protected void setUp() throws Exception { - numberOfConsumers = 1; - numberofProducers = 1; - super.setUp(); - } - - @Override - protected PerfProducer createProducer(ConnectionFactory fac, - Destination dest, - int number, - byte[] payload) throws JMSException { - PerfProducer pp = new PerfProducer(fac, dest, payload); - pp.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - //pp.setTimeToLive(100); - return pp; - } - - @Override - protected PerfConsumer createConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { - PerfConsumer result = new PerfConsumer(fac, dest); - result.setInitialDelay(10 * 1000); - boolean enableAudit = numberOfConsumers <= 1; - System.err.println("Enable Audit = " + enableAudit); - result.setEnableAudit(enableAudit); - - return result; - } - - @Override - protected void configureBroker(BrokerService answer, String uri) throws Exception { - // answer.setPersistent(false); - final List policyEntries = new ArrayList<>(); - final PolicyEntry entry = new PolicyEntry(); - entry.setQueue(">"); - entry.setMemoryLimit(1024 * 1024 * 1); // Set to 1 MB - entry.setOptimizedDispatch(true); - entry.setLazyDispatch(true); - policyEntries.add(entry); - - final PolicyMap policyMap = new PolicyMap(); - policyMap.setPolicyEntries(policyEntries); - answer.setDestinationPolicy(policyMap); - super.configureBroker(answer, uri); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentTopicTest.java deleted file mode 100644 index df0b8c55b6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleNonPersistentTopicTest.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.activemq.perf; - -import javax.jms.ConnectionFactory; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; - -/** - * - */ -public class SimpleNonPersistentTopicTest extends SimpleTopicTest { - - @Override - protected PerfProducer createProducer(ConnectionFactory fac, - Destination dest, - int number, - byte[] payload) throws JMSException { - PerfProducer pp = new PerfProducer(fac, dest, payload); - pp.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - return pp; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleQueueTest.java deleted file mode 100644 index 615c2e110f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleQueueTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.perf; - -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Session; - -/** - * - */ -public class SimpleQueueTest extends SimpleTopicTest { - - protected long initialConsumerDelay = 0; - protected long consumerSleep = 0; - - @Override - protected Destination createDestination(Session s, String destinationName) throws JMSException { - return s.createQueue(destinationName); - } - - @Override - protected void setUp() throws Exception { - numberOfConsumers = 1; - super.setUp(); - } - - @Override - protected PerfConsumer createConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { - PerfConsumer consumer = new PerfConsumer(fac, dest); - consumer.setInitialDelay(this.initialConsumerDelay); - consumer.setSleepDuration(this.consumerSleep); - boolean enableAudit = numberOfConsumers <= 1; - System.err.println("Enable Audit = " + enableAudit); - consumer.setEnableAudit(enableAudit); - return consumer; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleTopicTest.java deleted file mode 100644 index d32d705858..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SimpleTopicTest.java +++ /dev/null @@ -1,209 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.perf; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Session; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class SimpleTopicTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(SimpleTopicTest.class); - - protected BrokerService broker; - protected String clientURI = "tcp://localhost:61616?wireFormat.cacheEnabled=true&wireFormat.tightEncodingEnabled=true&jms.useAsyncSend=false&wireFormat.maxInactivityDuration=0"; - // protected String clientURI="tcp://localhost:61616"; - protected String bindAddress = "tcp://localhost:61616?wireFormat.maxInactivityDuration=0"; - // protected String bindAddress = "tcp://localhost:61616"; - // protected String bindAddress="vm://localhost?marshal=true"; - // protected String bindAddress="vm://localhost"; - protected PerfProducer[] producers; - protected PerfConsumer[] consumers; - protected String destinationName = getClass().getName(); - protected int sampleCount = 20; - protected long sampleInternal = 10000; - protected int numberOfDestinations = 1; - protected int numberOfConsumers = 1; - protected int numberofProducers = 1; - protected int totalNumberOfProducers; - protected int totalNumberOfConsumers; - protected int playloadSize = 12; - protected byte[] array; - protected ConnectionFactory factory; - - /** - * Sets up a test where the producer and consumer have their own connection. - * - * @see junit.framework.TestCase#setUp() - */ - @Override - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(bindAddress); - } - factory = createConnectionFactory(clientURI); - Connection con = factory.createConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - - LOG.info("Running " + numberofProducers + " producer(s) and " + numberOfConsumers + " consumer(s) per " + numberOfDestinations + " Destination(s)"); - - totalNumberOfConsumers = numberOfConsumers * numberOfDestinations; - totalNumberOfProducers = numberofProducers * numberOfDestinations; - producers = new PerfProducer[totalNumberOfProducers]; - consumers = new PerfConsumer[totalNumberOfConsumers]; - int consumerCount = 0; - int producerCount = 0; - for (int k = 0; k < numberOfDestinations; k++) { - Destination destination = createDestination(session, destinationName + ":" + k); - LOG.info("Testing against destination: " + destination); - for (int i = 0; i < numberOfConsumers; i++) { - consumers[consumerCount] = createConsumer(factory, destination, consumerCount); - consumerCount++; - } - for (int i = 0; i < numberofProducers; i++) { - array = new byte[playloadSize]; - for (int j = i; j < array.length; j++) { - array[j] = (byte) j; - } - producers[producerCount] = createProducer(factory, destination, i, array); - producerCount++; - } - } - con.close(); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - for (int i = 0; i < numberOfConsumers; i++) { - consumers[i].shutDown(); - } - for (int i = 0; i < numberofProducers; i++) { - producers[i].shutDown(); - } - if (broker != null) { - broker.stop(); - broker = null; - } - } - - protected Destination createDestination(Session s, String destinationName) throws JMSException { - return s.createTopic(destinationName); - } - - /** - * Factory method to create a new broker - * - * @throws Exception - */ - protected BrokerService createBroker(String uri) throws Exception { - BrokerService answer = new BrokerService(); - configureBroker(answer, uri); - answer.start(); - return answer; - } - - protected PerfProducer createProducer(ConnectionFactory fac, - Destination dest, - int number, - byte[] payload) throws JMSException { - return new PerfProducer(fac, dest, payload); - } - - protected PerfConsumer createConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { - return new PerfConsumer(fac, dest); - } - - protected void configureBroker(BrokerService answer, String uri) throws Exception { - answer.setDeleteAllMessagesOnStartup(true); - answer.addConnector(uri); - answer.setUseShutdownHook(false); - } - - protected ActiveMQConnectionFactory createConnectionFactory(String uri) throws Exception { - return new ActiveMQConnectionFactory(uri); - } - - public void testPerformance() throws JMSException, InterruptedException { - for (int i = 0; i < totalNumberOfConsumers; i++) { - consumers[i].start(); - } - for (int i = 0; i < totalNumberOfProducers; i++) { - producers[i].start(); - } - LOG.info("Sampling performance " + sampleCount + " times at a " + sampleInternal + " ms interval."); - for (int i = 0; i < sampleCount; i++) { - Thread.sleep(sampleInternal); - dumpProducerRate(); - dumpConsumerRate(); - } - for (int i = 0; i < totalNumberOfProducers; i++) { - producers[i].stop(); - } - for (int i = 0; i < totalNumberOfConsumers; i++) { - consumers[i].stop(); - } - } - - @SuppressWarnings("unused") - protected void dumpProducerRate() { - int totalRate = 0; - int totalCount = 0; - String producerString = "Producers:"; - for (int i = 0; i < producers.length; i++) { - PerfRate rate = producers[i].getRate().cloneAndReset(); - totalRate += rate.getRate(); - totalCount += rate.getTotalCount(); - producerString += "[" + i + ":" + rate.getRate() + "," + rate.getTotalCount() + "];"; - } - if (producers != null && producers.length > 0) { - int avgRate = totalRate / producers.length; - System.out.println("Avg producer rate = " + avgRate + " msg/sec | Total rate = " + totalRate + ", sent = " + totalCount); - // System.out.println(producerString); - } - } - - protected void dumpConsumerRate() { - int totalRate = 0; - int totalCount = 0; - String consumerString = "Consumers:"; - for (int i = 0; i < consumers.length; i++) { - PerfRate rate = consumers[i].getRate().cloneAndReset(); - totalRate += rate.getRate(); - totalCount += rate.getTotalCount(); - consumerString += "[" + i + ":" + rate.getRate() + "," + rate.getTotalCount() + "];"; - } - if (consumers != null && consumers.length > 0) { - int avgRate = totalRate / consumers.length; - System.out.println("Avg consumer rate = " + avgRate + " msg/sec | Total rate = " + totalRate + ", received = " + totalCount); - System.out.println(consumerString); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowConsumer.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowConsumer.java deleted file mode 100644 index a79721673a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowConsumer.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.activemq.perf; - -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class SlowConsumer extends PerfConsumer { - - private static final transient Logger LOG = LoggerFactory.getLogger(SlowConsumer.class); - - public SlowConsumer(ConnectionFactory fac, Destination dest, String consumerName) throws JMSException { - super(fac, dest, consumerName); - } - - public SlowConsumer(ConnectionFactory fac, Destination dest) throws JMSException { - super(fac, dest, null); - } - - @Override - public void onMessage(Message msg) { - super.onMessage(msg); - LOG.debug("GOT A MSG " + msg); - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowConsumerTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowConsumerTopicTest.java deleted file mode 100644 index fbdd0ad28d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowConsumerTopicTest.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.activemq.perf; - -import javax.jms.ConnectionFactory; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ActiveMQPrefetchPolicy; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.xbean.BrokerFactoryBean; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; - -/** - * - */ -public class SlowConsumerTopicTest extends SimpleTopicTest { - - protected PerfConsumer[] slowConsumers; - - @Override - protected void setUp() throws Exception { - - playloadSize = 10 * 1024; - super.setUp(); - } - - @Override - protected PerfConsumer createConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { - PerfConsumer result = new SlowConsumer(fac, dest); - return result; - } - - @Override - protected PerfProducer createProducer(ConnectionFactory fac, - Destination dest, - int number, - byte[] payload) throws JMSException { - PerfProducer result = super.createProducer(fac, dest, number, payload); - result.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - result.setSleep(10); - return result; - } - - @Override - protected BrokerService createBroker(String url) throws Exception { - Resource resource = new ClassPathResource("org/apache/activemq/perf/slowConsumerBroker.xml"); - System.err.println("CREATE BROKER FROM " + resource); - BrokerFactoryBean factory = new BrokerFactoryBean(resource); - factory.afterPropertiesSet(); - BrokerService broker = factory.getBroker(); - - broker.start(); - return broker; - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory(String uri) throws Exception { - ActiveMQConnectionFactory result = super.createConnectionFactory(uri); - ActiveMQPrefetchPolicy policy = new ActiveMQPrefetchPolicy(); - policy.setTopicPrefetch(10); - result.setPrefetchPolicy(policy); - return result; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowDurableConsumerTopicTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowDurableConsumerTopicTest.java deleted file mode 100644 index 42e03e868c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/SlowDurableConsumerTopicTest.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.activemq.perf; - -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.JMSException; - -/** - * - */ -public class SlowDurableConsumerTopicTest extends SlowConsumerTopicTest { - - protected PerfConsumer[] slowConsumers; - protected int numberOfSlowConsumers = 1; - - protected PerfConsumer createSlowConsumer(ConnectionFactory fac, Destination dest, int number) throws JMSException { - return new SlowConsumer(fac, dest, "durableSlowConsumer" + number); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/TemporaryTopicMemoryAllocationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/TemporaryTopicMemoryAllocationTest.java deleted file mode 100644 index aca01b73d8..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/TemporaryTopicMemoryAllocationTest.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.activemq.perf; - -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Session; - -/** - * - */ -public class TemporaryTopicMemoryAllocationTest extends MemoryAllocationTest { - - public TemporaryTopicMemoryAllocationTest() { - super(); - } - - @Override - protected Destination getDestination(Session session) throws JMSException { - return session.createTemporaryTopic(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/kahaBroker.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/kahaBroker.xml deleted file mode 100644 index 1262436d20..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/kahaBroker.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/kahadbBroker.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/kahadbBroker.xml deleted file mode 100644 index 226a441eaf..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/kahadbBroker.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/networkSync.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/networkSync.xml deleted file mode 100644 index 7fb9dceb5b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/networkSync.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/slowConsumerBroker.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/slowConsumerBroker.xml deleted file mode 100644 index ac0e8bcec3..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/perf/slowConsumerBroker.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/plugin/BrokerStatisticsPluginTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/plugin/BrokerStatisticsPluginTest.java deleted file mode 100644 index 4cb2c46e09..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/plugin/BrokerStatisticsPluginTest.java +++ /dev/null @@ -1,213 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.plugin; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.MapMessage; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; -import java.net.URI; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerPlugin; -import org.apache.activemq.broker.BrokerService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * A BrokerStatisticsPluginTest - * A testcase for https://issues.apache.org/activemq/browse/AMQ-2379 - */ -public class BrokerStatisticsPluginTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(BrokerStatisticsPluginTest.class); - - private Connection connection; - private BrokerService broker; - - public void testBrokerStats() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue replyTo = session.createTemporaryQueue(); - MessageConsumer consumer = session.createConsumer(replyTo); - Queue query = session.createQueue(StatisticsBroker.STATS_BROKER_PREFIX); - MessageProducer producer = session.createProducer(query); - Message msg = session.createMessage(); - msg.setJMSReplyTo(replyTo); - producer.send(msg); - MapMessage reply = (MapMessage) consumer.receive(10 * 1000); - assertNotNull(reply); - assertTrue(reply.getMapNames().hasMoreElements()); - assertTrue(reply.getJMSTimestamp() > 0); - assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority()); - /* - for (Enumeration e = reply.getMapNames();e.hasMoreElements();) { - String name = e.nextElement().toString(); - System.err.println(name+"="+reply.getObject(name)); - } - */ - } - - public void testBrokerStatsReset() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue replyTo = session.createTemporaryQueue(); - MessageConsumer consumer = session.createConsumer(replyTo); - Queue testQueue = session.createQueue("Test.Queue"); - Queue query = session.createQueue(StatisticsBroker.STATS_BROKER_PREFIX); - MessageProducer producer = session.createProducer(null); - - producer.send(testQueue, session.createMessage()); - - Message msg = session.createMessage(); - msg.setJMSReplyTo(replyTo); - producer.send(query, msg); - MapMessage reply = (MapMessage) consumer.receive(10 * 1000); - assertNotNull(reply); - assertTrue(reply.getMapNames().hasMoreElements()); - assertTrue(reply.getLong("enqueueCount") >= 1); - - msg = session.createMessage(); - msg.setBooleanProperty(StatisticsBroker.STATS_BROKER_RESET_HEADER, true); - msg.setJMSReplyTo(replyTo); - producer.send(query, msg); - reply = (MapMessage) consumer.receive(10 * 1000); - assertNotNull(reply); - assertTrue(reply.getMapNames().hasMoreElements()); - assertEquals(0, reply.getLong("enqueueCount")); - assertTrue(reply.getJMSTimestamp() > 0); - assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority()); - } - - public void testDestinationStats() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue replyTo = session.createTemporaryQueue(); - MessageConsumer consumer = session.createConsumer(replyTo); - Queue testQueue = session.createQueue("Test.Queue"); - MessageProducer producer = session.createProducer(null); - Queue query = session.createQueue(StatisticsBroker.STATS_DESTINATION_PREFIX + testQueue.getQueueName()); - Message msg = session.createMessage(); - - producer.send(testQueue, msg); - - msg.setJMSReplyTo(replyTo); - producer.send(query, msg); - MapMessage reply = (MapMessage) consumer.receive(10 * 1000); - assertNotNull(reply); - assertTrue(reply.getMapNames().hasMoreElements()); - assertTrue(reply.getJMSTimestamp() > 0); - assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority()); - /* - for (Enumeration e = reply.getMapNames();e.hasMoreElements();) { - String name = e.nextElement().toString(); - System.err.println(name+"="+reply.getObject(name)); - } - */ - } - - public void testDestinationStatsWithDot() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue replyTo = session.createTemporaryQueue(); - MessageConsumer consumer = session.createConsumer(replyTo); - Queue testQueue = session.createQueue("Test.Queue"); - MessageProducer producer = session.createProducer(null); - Queue query = session.createQueue(StatisticsBroker.STATS_DESTINATION_PREFIX + "." + testQueue.getQueueName()); - Message msg = session.createMessage(); - - producer.send(testQueue, msg); - - msg.setJMSReplyTo(replyTo); - producer.send(query, msg); - MapMessage reply = (MapMessage) consumer.receive(10 * 1000); - assertNotNull(reply); - assertTrue(reply.getMapNames().hasMoreElements()); - assertTrue(reply.getJMSTimestamp() > 0); - assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority()); - /* - for (Enumeration e = reply.getMapNames();e.hasMoreElements();) { - String name = e.nextElement().toString(); - System.err.println(name+"="+reply.getObject(name)); - } - */ - } - - @SuppressWarnings("unused") - public void testSubscriptionStats() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue replyTo = session.createTemporaryQueue(); - MessageConsumer consumer = session.createConsumer(replyTo); - Queue testQueue = session.createQueue("Test.Queue"); - MessageConsumer testConsumer = session.createConsumer(testQueue); - MessageProducer producer = session.createProducer(null); - Queue query = session.createQueue(StatisticsBroker.STATS_SUBSCRIPTION_PREFIX); - Message msg = session.createMessage(); - - producer.send(testQueue, msg); - - msg.setJMSReplyTo(replyTo); - producer.send(query, msg); - MapMessage reply = (MapMessage) consumer.receive(10 * 1000); - assertNotNull(reply); - assertTrue(reply.getMapNames().hasMoreElements()); - assertTrue(reply.getJMSTimestamp() > 0); - assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority()); - - /*for (Enumeration e = reply.getMapNames();e.hasMoreElements();) { - String name = e.nextElement().toString(); - System.err.println(name+"="+reply.getObject(name)); - }*/ - } - - @Override - protected void setUp() throws Exception { - broker = createBroker(); - ConnectionFactory factory = new ActiveMQConnectionFactory(broker.getTransportConnectorURIsAsMap().get("tcp")); - connection = factory.createConnection(); - connection.start(); - } - - @Override - protected void tearDown() throws Exception { - if (this.connection != null) { - this.connection.close(); - } - if (this.broker != null) { - this.broker.stop(); - } - } - - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - BrokerPlugin[] plugins = new BrokerPlugin[1]; - plugins[0] = new StatisticsBrokerPlugin(); - answer.setPlugins(plugins); - answer.setDeleteAllMessagesOnStartup(true); - answer.addConnector("tcp://localhost:0"); - answer.start(); - return answer; - } - - protected BrokerService createBroker(String uri) throws Exception { - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/plugin/statistics-plugin-broker.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/plugin/statistics-plugin-broker.xml deleted file mode 100644 index ad3933a0c1..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/plugin/statistics-plugin-broker.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/pool/JmsSendReceiveTwoConnectionsWithSenderUsingPoolTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/pool/JmsSendReceiveTwoConnectionsWithSenderUsingPoolTest.java deleted file mode 100644 index 0792b2e540..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/pool/JmsSendReceiveTwoConnectionsWithSenderUsingPoolTest.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.activemq.pool; - -import javax.jms.Connection; - -import org.apache.activemq.test.JmsTopicSendReceiveWithTwoConnectionsTest; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class JmsSendReceiveTwoConnectionsWithSenderUsingPoolTest extends JmsTopicSendReceiveWithTwoConnectionsTest { - - protected static final Logger LOG = LoggerFactory.getLogger(JmsSendReceiveTwoConnectionsWithSenderUsingPoolTest.class); - protected PooledConnectionFactory senderConnectionFactory = new PooledConnectionFactory("vm://localhost?broker.persistent=false"); - - @Override - protected Connection createSendConnection() throws Exception { - return senderConnectionFactory.createConnection(); - } - - @Override - protected void setUp() throws Exception { - verbose = true; - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - senderConnectionFactory.stop(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/AMQ4889Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/AMQ4889Test.java deleted file mode 100644 index b0d11436a5..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/AMQ4889Test.java +++ /dev/null @@ -1,134 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.proxy; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.JMSSecurityException; -import javax.jms.Session; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerPlugin; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.security.AuthenticationUser; -import org.apache.activemq.security.SimpleAuthenticationPlugin; -import org.apache.activemq.util.Wait; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -public class AMQ4889Test { - - protected static final Logger LOG = LoggerFactory.getLogger(AMQ4889Test.class); - - public static final String USER = "user"; - public static final String GOOD_USER_PASSWORD = "password"; - public static final String WRONG_PASSWORD = "wrongPassword"; - public static final String PROXY_URI = "tcp://localhost:6002"; - public static final String LOCAL_URI = "tcp://localhost:6001"; - - protected BrokerService brokerService; - private ProxyConnector proxyConnector; - protected TransportConnector transportConnector; - protected ConnectionFactory connectionFactory; - - private static final Integer ITERATIONS = 100; - - protected BrokerService createBroker() throws Exception { - brokerService = new BrokerService(); - brokerService.setPersistent(false); - - ArrayList plugins = new ArrayList<>(); - BrokerPlugin authenticationPlugin = configureAuthentication(); - plugins.add(authenticationPlugin); - BrokerPlugin[] array = new BrokerPlugin[plugins.size()]; - brokerService.setPlugins(plugins.toArray(array)); - - transportConnector = brokerService.addConnector(LOCAL_URI); - proxyConnector = new ProxyConnector(); - proxyConnector.setName("proxy"); - proxyConnector.setBind(new URI(PROXY_URI)); - proxyConnector.setRemote(new URI(LOCAL_URI)); - brokerService.addProxyConnector(proxyConnector); - - brokerService.start(); - brokerService.waitUntilStarted(); - - return brokerService; - } - - protected BrokerPlugin configureAuthentication() throws Exception { - List users = new ArrayList<>(); - users.add(new AuthenticationUser(USER, GOOD_USER_PASSWORD, "users")); - SimpleAuthenticationPlugin authenticationPlugin = new SimpleAuthenticationPlugin(users); - - return authenticationPlugin; - } - - @Before - public void setUp() throws Exception { - brokerService = createBroker(); - connectionFactory = new ActiveMQConnectionFactory(PROXY_URI); - } - - @After - public void tearDown() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } - - @Test(timeout = 1 * 60 * 1000) - public void testForConnectionLeak() throws Exception { - Integer expectedConnectionCount = 0; - for (int i = 0; i < ITERATIONS; i++) { - try { - if (i % 2 == 0) { - LOG.debug("Iteration {} adding bad connection", i); - Connection connection = connectionFactory.createConnection(USER, WRONG_PASSWORD); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - fail("createSession should fail"); - } else { - LOG.debug("Iteration {} adding good connection", i); - Connection connection = connectionFactory.createConnection(USER, GOOD_USER_PASSWORD); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - expectedConnectionCount++; - } - // - } catch (JMSSecurityException e) { - } - LOG.debug("Iteration {} Connections? {}", i, proxyConnector.getConnectionCount()); - } - final Integer val = expectedConnectionCount; - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return val.equals(proxyConnector.getConnectionCount()); - } - }, 20); - assertEquals(val, proxyConnector.getConnectionCount()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyConnectorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyConnectorTest.java deleted file mode 100644 index 82bc7f77e4..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyConnectorTest.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.proxy; - -import javax.jms.DeliveryMode; - -import junit.framework.Test; - -import org.apache.activemq.broker.StubConnection; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ConnectionInfo; -import org.apache.activemq.command.ConsumerInfo; -import org.apache.activemq.command.Message; -import org.apache.activemq.command.ProducerInfo; -import org.apache.activemq.command.SessionInfo; - -public class ProxyConnectorTest extends ProxyTestSupport { - - public ActiveMQDestination destination; - public byte destinationType; - public int deliveryMode; - - public static Test suite() { - return suite(ProxyConnectorTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - } - - public void initCombosForTestSendAndConsume() { - addCombinationValues("deliveryMode", new Object[]{Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destinationType", new Object[]{Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); - } - - public void testSendAndConsume() throws Exception { - - // Start a producer on local broker using the proxy - StubConnection connection1 = createProxyConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ProducerInfo producerInfo = createProducerInfo(sessionInfo1); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.send(producerInfo); - - destination = createDestinationInfo(connection1, connectionInfo1, destinationType); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - connection1.send(consumerInfo1); - - // Start a consumer on a remote broker using a proxy connection. - StubConnection connection2 = createRemoteProxyConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - connection2.send(consumerInfo2); - - // Give broker enough time to receive and register the consumer info - // Either that or make consumer retroactive - try { - Thread.sleep(2000); - } catch (Exception e) { - e.printStackTrace(); - } - - // Send the message to the local broker. - connection1.request(createMessage(producerInfo, destination, deliveryMode)); - - // Verify that the message Was sent to the remote broker and the local - // broker. - Message m; - m = receiveMessage(connection1); - assertNotNull(m); - assertNoMessagesLeft(connection1); - - m = receiveMessage(connection2); - assertNotNull(m); - assertNoMessagesLeft(connection2); - - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyFailoverTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyFailoverTest.java deleted file mode 100644 index 561de3f7dc..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyFailoverTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.proxy; - -import javax.jms.Connection; -import javax.jms.Session; -import java.net.URI; -import java.util.concurrent.TimeUnit; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.util.ConsumerThread; -import org.apache.activemq.util.ProducerThread; - -public class ProxyFailoverTest extends TestCase { - - BrokerService proxyBroker; - BrokerService remoteBroker; - - @Override - protected void setUp() throws Exception { - startRemoteBroker(true); - proxyBroker = new BrokerService(); - ProxyConnector connector = new ProxyConnector(); - connector.setBind(new URI("tcp://localhost:51618")); - connector.setProxyToLocalBroker(false); - connector.setRemote(new URI("failover:(tcp://localhost:61616)")); - proxyBroker.addProxyConnector(connector); - proxyBroker.setPersistent(false); - proxyBroker.setUseJmx(false); - proxyBroker.start(); - proxyBroker.waitUntilStarted(); - } - - @Override - protected void tearDown() throws Exception { - proxyBroker.stop(); - proxyBroker.waitUntilStopped(); - remoteBroker.stop(); - remoteBroker.waitUntilStopped(); - } - - public void testFailover() throws Exception { - ActiveMQConnectionFactory producerFactory = new ActiveMQConnectionFactory("failover:(tcp://localhost:61616,tcp://localhost:61626)?randomize=false"); - Connection producerConnection = producerFactory.createConnection(); - producerConnection.start(); - Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ProducerThread producer = new ProducerThread(producerSession, producerSession.createQueue("ProxyTest")); - producer.setSleep(10); - producer.start(); - - ActiveMQConnectionFactory consumerFactory = new ActiveMQConnectionFactory("tcp://localhost:51618"); - Connection consumerConnection = consumerFactory.createConnection(); - consumerConnection.start(); - Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ConsumerThread consumer = new ConsumerThread(consumerSession, consumerSession.createQueue("ProxyTest")); - consumer.start(); - - TimeUnit.SECONDS.sleep(15); - - remoteBroker.stop(); - remoteBroker.waitUntilStopped(); - startRemoteBroker(false); - - producer.join(); - consumer.join(); - - assertEquals(1000, consumer.getReceived()); - } - - protected void startRemoteBroker(boolean delete) throws Exception { - remoteBroker = new BrokerService(); - remoteBroker.addConnector("tcp://localhost:61616"); - if (delete) { - remoteBroker.deleteAllMessages(); - } - remoteBroker.setUseJmx(false); - remoteBroker.start(); - remoteBroker.waitUntilStarted(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyTestSupport.java deleted file mode 100644 index 7e6e1c603b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/proxy/ProxyTestSupport.java +++ /dev/null @@ -1,141 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.proxy; - -import java.net.URI; -import java.util.ArrayList; -import java.util.Iterator; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.BrokerTestSupport; -import org.apache.activemq.broker.StubConnection; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.store.PersistenceAdapter; -import org.apache.activemq.transport.Transport; -import org.apache.activemq.transport.TransportFactory; -import org.apache.activemq.usage.SystemUsage; - -public class ProxyTestSupport extends BrokerTestSupport { - - protected ArrayList connections = new ArrayList<>(); - - protected TransportConnector connector; - - protected PersistenceAdapter remotePersistenceAdapter; - protected BrokerService remoteBroker; - protected SystemUsage remoteMemoryManager; - protected TransportConnector remoteConnector; - private ProxyConnector proxyConnector; - private ProxyConnector remoteProxyConnector; - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService service = new BrokerService(); - service.setBrokerName("broker1"); - service.setPersistent(false); - service.setUseJmx(false); - - connector = service.addConnector(getLocalURI()); - proxyConnector = new ProxyConnector(); - proxyConnector.setName("proxy"); - proxyConnector.setBind(new URI(getLocalProxyURI())); - proxyConnector.setRemote(new URI("fanout:static://" + getRemoteURI())); - service.addProxyConnector(proxyConnector); - - return service; - } - - protected BrokerService createRemoteBroker() throws Exception { - BrokerService service = new BrokerService(); - service.setBrokerName("broker2"); - service.setPersistent(false); - service.setUseJmx(false); - - remoteConnector = service.addConnector(getRemoteURI()); - remoteProxyConnector = new ProxyConnector(); - remoteProxyConnector.setName("remoteProxy"); - remoteProxyConnector.setBind(new URI(getRemoteProxyURI())); - remoteProxyConnector.setRemote(new URI("fanout:static://" + getLocalURI())); - service.addProxyConnector(remoteProxyConnector); - - return service; - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - remoteBroker = createRemoteBroker(); - remoteBroker.start(); - } - - @Override - protected void tearDown() throws Exception { - for (Iterator iter = connections.iterator(); iter.hasNext(); ) { - StubConnection connection = iter.next(); - connection.stop(); - iter.remove(); - } - remoteBroker.stop(); - super.tearDown(); - } - - protected String getRemoteURI() { - return "tcp://localhost:6171"; - } - - protected String getLocalURI() { - return "tcp://localhost:6161"; - } - - protected String getRemoteProxyURI() { - return "tcp://localhost:6162"; - } - - protected String getLocalProxyURI() { - return "tcp://localhost:6172"; - } - - @Override - protected StubConnection createConnection() throws Exception { - Transport transport = TransportFactory.connect(connector.getServer().getConnectURI()); - StubConnection connection = new StubConnection(transport); - connections.add(connection); - return connection; - } - - protected StubConnection createRemoteConnection() throws Exception { - Transport transport = TransportFactory.connect(remoteConnector.getServer().getConnectURI()); - StubConnection connection = new StubConnection(transport); - connections.add(connection); - return connection; - } - - protected StubConnection createProxyConnection() throws Exception { - Transport transport = TransportFactory.connect(proxyConnector.getServer().getConnectURI()); - StubConnection connection = new StubConnection(transport); - connections.add(connection); - return connection; - } - - protected StubConnection createRemoteProxyConnection() throws Exception { - Transport transport = TransportFactory.connect(remoteProxyConnector.getServer().getConnectURI()); - StubConnection connection = new StubConnection(transport); - connections.add(connection); - return connection; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AMQauth.ldif b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AMQauth.ldif deleted file mode 100644 index 45d8ae0ce5..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AMQauth.ldif +++ /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. -## --------------------------------------------------------------------------- - -dn: o=ActiveMQ,ou=system -objectclass: organization -objectclass: top -o: ActiveMQ - -dn: ou=users,o=ActiveMQ,ou=system -objectclass: organizationalUnit -objectclass: top -ou: users - -dn: uid=ngcutura,ou=users,o=ActiveMQ,ou=system -objectclass: inetOrgPerson -objectclass: organizationalPerson -objectclass: person -objectclass: top -cn: Goran Cutura -sn: Cutura -uid: ngcutura -userpassword:: e3NoYX0wZE9sTGxnU2ZRT3NSaFR5OGx3NUM3K1hlSkE9 - -dn: cn=roles,uid=ngcutura,ou=users,o=ActiveMQ,ou=system -objectclass: groupOfUniqueNames -objectclass: top -cn: roles -uniquemember: uid=ngcutura - -dn: ou=destinations,o=ActiveMQ,ou=system -objectclass: organizationalUnit -objectclass: top -ou: destinations - -dn: ou=topics,ou=destinations,o=ActiveMQ,ou=system -objectclass: organizationalUnit -objectclass: top -ou: topics - -dn: uid=topic1,ou=topics,ou=destinations,o=ActiveMQ,ou=system -objectclass: uidObject -objectclass: top -objectclass: applicationProcess -uid: topic1 -cn: topic1 - -dn: cn=admin,uid=topic1,ou=topics,ou=destinations,o=ActiveMQ,ou=system -objectclass: groupOfUniqueNames -objectclass: top -cn: admin -uniquemember: uid=role1 - -dn: cn=read,uid=topic1,ou=topics,ou=destinations,o=ActiveMQ,ou=system -objectclass: groupOfUniqueNames -objectclass: top -cn: read -uniquemember: uid=role2 - -dn: cn=write,uid=topic1,ou=topics,ou=destinations,o=ActiveMQ,ou=system -objectclass: groupOfUniqueNames -objectclass: top -cn: write -uniquemember: uid=role3 - -dn: ou=queues,ou=destinations,o=ActiveMQ,ou=system -objectclass: organizationalUnit -objectclass: top -ou: queues - -dn: uid=queue1,ou=queues,ou=destinations,o=ActiveMQ,ou=system -objectclass: applicationProcess -objectclass: uidObject -objectclass: top -uid: queue1 -cn: queue1 - -dn: cn=read,uid=queue1,ou=queues,ou=destinations,o=ActiveMQ,ou=system -objectclass: groupOfUniqueNames -objectclass: top -cn: read -uniquemember: uid=role1 - -dn: cn=write,uid=queue1,ou=queues,ou=destinations,o=ActiveMQ,ou=system -objectclass: groupOfUniqueNames -objectclass: top -cn: write -uniquemember: uid=role1 -uniquemember: uid=role2 - -dn: cn=admin,uid=queue1,ou=queues,ou=destinations,o=ActiveMQ,ou=system -objectclass: groupOfUniqueNames -objectclass: top -cn: admin -uniquemember: uid=role1 - -dn: uid=ActiveMQ.Advisory,ou=topics,ou=destinations,o=ActiveMQ,ou=system -objectclass: uidObject -objectclass: top -objectclass: applicationProcess -uid: ActiveMQ.Advisory -cn: ActiveMQ.Advisory - -dn: cn=admin,uid=ActiveMQ.Advisory,ou=topics,ou=destinations,o=ActiveMQ,ou=system -objectclass: groupOfUniqueNames -objectclass: top -cn: admin -uniquemember: uid=role1 - -dn: cn=read,uid=ActiveMQ.Advisory,ou=topics,ou=destinations,o=ActiveMQ,ou=system -objectclass: groupOfUniqueNames -objectclass: top -cn: read -uniquemember: uid=role2 - -dn: cn=write,uid=ActiveMQ.Advisory,ou=topics,ou=destinations,o=ActiveMQ,ou=system -objectclass: groupOfUniqueNames -objectclass: top -cn: write -uniquemember: uid=role3 - -dn: uid=ActiveMQ.Temp,ou=topics,ou=destinations,o=ActiveMQ,ou=system -objectclass: uidObject -objectclass: top -objectclass: applicationProcess -uid: ActiveMQ.Temp -cn: ActiveMQ.Temp - -dn: cn=admin,uid=ActiveMQ.Temp,ou=topics,ou=destinations,o=ActiveMQ,ou=system -objectclass: groupOfUniqueNames -objectclass: top -cn: admin -uniquemember: uid=role1 - -dn: cn=read,uid=ActiveMQ.Temp,ou=topics,ou=destinations,o=ActiveMQ,ou=system -objectclass: groupOfUniqueNames -objectclass: top -cn: read -uniquemember: uid=role2 - -dn: cn=write,uid=ActiveMQ.Temp,ou=topics,ou=destinations,o=ActiveMQ,ou=system -objectclass: groupOfUniqueNames -objectclass: top -cn: write -uniquemember: uid=role3 - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AbstractCachedLDAPAuthorizationMapLegacyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AbstractCachedLDAPAuthorizationMapLegacyTest.java deleted file mode 100644 index a039bfc9b7..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AbstractCachedLDAPAuthorizationMapLegacyTest.java +++ /dev/null @@ -1,424 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.security; - -import javax.naming.Context; -import javax.naming.NameClassPair; -import javax.naming.NamingEnumeration; -import javax.naming.directory.DirContext; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.jaas.GroupPrincipal; -import org.apache.activemq.util.Wait; -import org.apache.directory.api.ldap.model.ldif.LdifEntry; -import org.apache.directory.api.ldap.model.ldif.LdifReader; -import org.apache.directory.api.ldap.model.message.ModifyRequest; -import org.apache.directory.api.ldap.model.message.ModifyRequestImpl; -import org.apache.directory.api.ldap.model.name.Dn; -import org.apache.directory.api.ldap.model.name.Rdn; -import org.apache.directory.ldap.client.api.LdapConnection; -import org.apache.directory.server.core.integ.AbstractLdapTestUnit; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -public abstract class AbstractCachedLDAPAuthorizationMapLegacyTest extends AbstractLdapTestUnit { - - static final GroupPrincipal GUESTS = new GroupPrincipal("guests"); - static final GroupPrincipal USERS = new GroupPrincipal("users"); - static final GroupPrincipal ADMINS = new GroupPrincipal("admins"); - - protected LdapConnection connection; - protected SimpleCachedLDAPAuthorizationMap map; - - @Before - public void setup() throws Exception { - connection = getLdapConnection(); - map = createMap(); - } - - @After - public void cleanup() throws Exception { - if (connection != null) { - try { - connection.close(); - } catch (IOException e) { - // Ignore - } - } - - if (map != null) { - map.destroy(); - } - } - - @Test - public void testQuery() throws Exception { - map.query(); - Set readACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + readACLs, 2, readACLs.size()); - assertTrue("Contains admin group", readACLs.contains(ADMINS)); - assertTrue("Contains users group", readACLs.contains(USERS)); - - Set failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED")); - assertEquals("set size: " + failedACLs, 0, failedACLs.size()); - } - - @Test - public void testSynchronousUpdate() throws Exception { - map.setRefreshInterval(1); - map.query(); - Set readACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + readACLs, 2, readACLs.size()); - assertTrue("Contains admin group", readACLs.contains(ADMINS)); - assertTrue("Contains users group", readACLs.contains(USERS)); - - Set failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED")); - assertEquals("set size: " + failedACLs, 0, failedACLs.size()); - - LdifReader reader = new LdifReader(getRemoveLdif()); - - for (LdifEntry entry : reader) { - connection.delete(entry.getDn()); - } - - reader.close(); - - assertTrue("did not get expected size. ", Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - return map.getReadACLs(new ActiveMQQueue("TEST.FOO")).size() == 0; - } - })); - - assertNull(map.getTempDestinationReadACLs()); - assertNull(map.getTempDestinationWriteACLs()); - assertNull(map.getTempDestinationAdminACLs()); - } - - @Test - public void testWildcards() throws Exception { - map.query(); - Set fooACLs = map.getReadACLs(new ActiveMQQueue("FOO.1")); - assertEquals("set size: " + fooACLs, 2, fooACLs.size()); - assertTrue("Contains admin group", fooACLs.contains(ADMINS)); - assertTrue("Contains users group", fooACLs.contains(USERS)); - - Set barACLs = map.getReadACLs(new ActiveMQQueue("BAR.2")); - assertEquals("set size: " + barACLs, 2, barACLs.size()); - assertTrue("Contains admin group", barACLs.contains(ADMINS)); - assertTrue("Contains users group", barACLs.contains(USERS)); - } - - @Test - public void testAdvisory() throws Exception { - map.query(); - Set readACLs = map.getReadACLs(new ActiveMQTopic("ActiveMQ.Advisory.Connection")); - assertEquals("set size: " + readACLs, 2, readACLs.size()); - assertTrue("Contains admin group", readACLs.contains(ADMINS)); - assertTrue("Contains users group", readACLs.contains(USERS)); - } - - @Test - public void testTemporary() throws Exception { - map.query(); - - Thread.sleep(1000); - Set readACLs = map.getTempDestinationReadACLs(); - assertEquals("set size: " + readACLs, 2, readACLs.size()); - assertTrue("Contains admin group", readACLs.contains(ADMINS)); - assertTrue("Contains users group", readACLs.contains(USERS)); - } - - @Test - public void testAdd() throws Exception { - map.query(); - - Set failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED")); - assertEquals("set size: " + failedACLs, 0, failedACLs.size()); - - LdifReader reader = new LdifReader(getAddLdif()); - - for (LdifEntry entry : reader) { - connection.add(entry.getEntry()); - } - - reader.close(); - - Thread.sleep(2000); - - failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED")); - assertEquals("set size: " + failedACLs, 2, failedACLs.size()); - } - - @Test - public void testRemove() throws Exception { - map.query(); - - Set failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 2, failedACLs.size()); - - LdifReader reader = new LdifReader(getRemoveLdif()); - - for (LdifEntry entry : reader) { - connection.delete(entry.getDn()); - } - - reader.close(); - Thread.sleep(2000); - - failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 0, failedACLs.size()); - - assertTrue(map.getTempDestinationReadACLs() == null || map.getTempDestinationReadACLs().isEmpty()); - assertTrue(map.getTempDestinationWriteACLs() == null || map.getTempDestinationWriteACLs().isEmpty()); - assertTrue(map.getTempDestinationAdminACLs() == null || map.getTempDestinationAdminACLs().isEmpty()); - } - - @Test - public void testRenameDestination() throws Exception { - map.query(); - - // Test for a destination rename - Set failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 2, failedACLs.size()); - - connection.rename(new Dn("cn=TEST.FOO," + getQueueBaseDn()), new Rdn("cn=TEST.BAR")); - - Thread.sleep(2000); - - failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 0, failedACLs.size()); - - failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.BAR")); - assertEquals("set size: " + failedACLs, 2, failedACLs.size()); - } - - @Test - public void testRenamePermission() throws Exception { - map.query(); - - // Test for a permission rename - connection.delete(new Dn("cn=Read,cn=TEST.FOO," + getQueueBaseDn())); - - Thread.sleep(2000); - - Set failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 0, failedACLs.size()); - - failedACLs = map.getWriteACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 2, failedACLs.size()); - - connection.rename(new Dn("cn=Write,cn=TEST.FOO," + getQueueBaseDn()), new Rdn("cn=Read")); - - Thread.sleep(2000); - - failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 2, failedACLs.size()); - - failedACLs = map.getWriteACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 0, failedACLs.size()); - } - - @Test - public void testChange() throws Exception { - map.query(); - - // Change permission entry - Set failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 2, failedACLs.size()); - - Dn dn = new Dn("cn=read,cn=TEST.FOO," + getQueueBaseDn()); - - ModifyRequest request = new ModifyRequestImpl(); - request.setName(dn); - setupModifyRequest(request); - - connection.modify(request); - - Thread.sleep(2000); - - failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 1, failedACLs.size()); - - // Change destination entry - request = new ModifyRequestImpl(); - request.setName(new Dn("cn=TEST.FOO," + getQueueBaseDn())); - request.add("description", "This is a description! In fact, it is a very good description."); - - connection.modify(request); - - Thread.sleep(2000); - - failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 1, failedACLs.size()); - } - - @Test - public void testRestartAsync() throws Exception { - testRestart(false); - } - - @Test - public void testRestartSync() throws Exception { - testRestart(true); - } - - public void testRestart(final boolean sync) throws Exception { - if (sync) { - // ldap connection can be slow to close - map.setRefreshInterval(1000); - } - map.query(); - - Set failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED")); - assertEquals("set size: " + failedACLs, 0, failedACLs.size()); - - failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 2, failedACLs.size()); - - getLdapServer().stop(); - - // wait for the context to be closed - // as we can't rely on ldar server isStarted() - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - if (sync) { - return !map.isContextAlive(); - } else { - return map.context == null; - } - } - }); - - failedACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOO")); - assertEquals("set size: " + failedACLs, 2, failedACLs.size()); - - getLdapServer().start(); - - Thread.sleep(2000); - - connection = getLdapConnection(); - - LdifReader reader = new LdifReader(getAddLdif()); - - for (LdifEntry entry : reader) { - connection.add(entry.getEntry()); - } - - reader.close(); - - assertTrue("did not get expected size. ", Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - return map.getReadACLs(new ActiveMQQueue("FAILED")).size() == 2; - } - })); - } - - protected SimpleCachedLDAPAuthorizationMap createMap() { - return new SimpleCachedLDAPAuthorizationMap(); - } - - protected abstract InputStream getAddLdif(); - - protected abstract InputStream getRemoveLdif(); - - protected void setupModifyRequest(ModifyRequest request) { - request.remove("member", "cn=users"); - } - - protected abstract String getQueueBaseDn(); - - protected abstract LdapConnection getLdapConnection() throws Exception; - - public static void cleanAndLoad(String deleteFromDn, - String ldifResourcePath, - String ldapHost, - int ldapPort, - String ldapUser, - String ldapPass, - DirContext context) throws Exception { - // Cleanup everything used for testing. - List dns = new LinkedList<>(); - dns.add(deleteFromDn); - - while (!dns.isEmpty()) { - String name = dns.get(dns.size() - 1); - Context currentContext = (Context) context.lookup(name); - NamingEnumeration namingEnum = currentContext.list(""); - - if (namingEnum.hasMore()) { - while (namingEnum.hasMore()) { - dns.add(namingEnum.next().getNameInNamespace()); - } - } else { - context.unbind(name); - dns.remove(dns.size() - 1); - } - } - - // A bit of a hacked approach to loading an LDIF into OpenLDAP since there isn't an easy way to do it - // otherwise. This approach invokes the command line tool programmatically but has - // to short-circuit the call to System.exit that the command line tool makes when it finishes. - // We are assuming that there isn't already a security manager in place. - final SecurityManager securityManager = new SecurityManager() { - - @Override - public void checkPermission(java.security.Permission permission) { - if (permission.getName().contains("exitVM")) { - throw new SecurityException("System.exit calls disabled for the moment."); - } - } - }; - - System.setSecurityManager(securityManager); - - File file = new File(AbstractCachedLDAPAuthorizationMapLegacyTest.class.getClassLoader().getResource(ldifResourcePath).toURI()); - - Class clazz = Class.forName("LDAPModify"); - Method mainMethod = clazz.getMethod("main", String[].class); - - try { - mainMethod.invoke(null, new Object[]{new String[]{"-v", "-h", ldapHost, "-p", String.valueOf(ldapPort), "-D", ldapUser, "-w", ldapPass, "-a", "-f", file.toString()}}); - } catch (InvocationTargetException e) { - if (!(e.getTargetException() instanceof SecurityException)) { - throw e; - } - } - - System.setSecurityManager(null); - } -} - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AbstractCachedLDAPAuthorizationModuleTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AbstractCachedLDAPAuthorizationModuleTest.java deleted file mode 100644 index 8bf3f32e5d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AbstractCachedLDAPAuthorizationModuleTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.security; - -import java.util.Set; - -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.jaas.UserPrincipal; -import org.apache.directory.api.ldap.model.message.ModifyRequest; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public abstract class AbstractCachedLDAPAuthorizationModuleTest extends AbstractCachedLDAPAuthorizationMapLegacyTest { - - static final UserPrincipal JDOE = new UserPrincipal("jdoe"); - - @Override - @Test - public void testQuery() throws Exception { - map.query(); - Set readACLs = map.getReadACLs(new ActiveMQQueue("TEST.FOOBAR")); - assertEquals("set size: " + readACLs, 3, readACLs.size()); - assertTrue("Contains admin group", readACLs.contains(ADMINS)); - assertTrue("Contains users group", readACLs.contains(USERS)); - assertTrue("Contains jdoe user", readACLs.contains(JDOE)); - - Set failedACLs = map.getReadACLs(new ActiveMQQueue("FAILED")); - assertEquals("set size: " + failedACLs, 0, failedACLs.size()); - - super.testQuery(); - } - - @Override - protected final void setupModifyRequest(ModifyRequest request) { - request.remove("member", getMemberAttributeValueForModifyRequest()); - } - - protected abstract String getMemberAttributeValueForModifyRequest(); - - @Override - protected SimpleCachedLDAPAuthorizationMap createMap() { - SimpleCachedLDAPAuthorizationMap map = super.createMap(); - map.setLegacyGroupMapping(false); - return map; - } -} - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AuthorizationMapTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AuthorizationMapTest.java deleted file mode 100644 index d8b0ee35f2..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/AuthorizationMapTest.java +++ /dev/null @@ -1,196 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.security; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import junit.framework.TestCase; - -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.filter.DestinationMapEntry; -import org.apache.activemq.jaas.GroupPrincipal; - -/** - * - * - */ -public class AuthorizationMapTest extends TestCase { - - static final GroupPrincipal USERS = new GroupPrincipal("users"); - static final GroupPrincipal ADMINS = new GroupPrincipal("admins"); - static final GroupPrincipal TEMP_DESTINATION_ADMINS = new GroupPrincipal("tempDestAdmins"); - - public void testAuthorizationMap() { - AuthorizationMap map = createAuthorizationMap(); - - Set readACLs = map.getReadACLs(new ActiveMQQueue("USERS.FOO.BAR")); - assertEquals("set size: " + readACLs, 2, readACLs.size()); - assertTrue("Contains users group", readACLs.contains(ADMINS)); - assertTrue("Contains users group", readACLs.contains(USERS)); - - } - - public void testCompositeDoesNotBypassAuthorizationMap() { - AuthorizationMap map = createAuthorizationMap(); - - Set readACLs = map.getReadACLs(new ActiveMQQueue("USERS.FOO.BAR,DENIED")); - assertEquals("set size: " + readACLs, 1, readACLs.size()); - assertTrue("Contains users group", readACLs.contains(ADMINS)); - } - - public void testAuthorizationMapWithTempDest() { - AuthorizationMap map = createAuthorizationMapWithTempDest(); - - Set readACLs = map.getReadACLs(new ActiveMQQueue("USERS.FOO.BAR")); - assertEquals("set size: " + readACLs, 2, readACLs.size()); - assertTrue("Contains users group", readACLs.contains(ADMINS)); - assertTrue("Contains users group", readACLs.contains(USERS)); - - Set tempAdminACLs = map.getTempDestinationAdminACLs(); - assertEquals("set size: " + tempAdminACLs, 1, tempAdminACLs.size()); - assertTrue("Contains users group", tempAdminACLs.contains(TEMP_DESTINATION_ADMINS)); - - } - - public void testWildcards() { - AuthorizationMap map = createWildcardAuthorizationMap(); - - Set readACLs = map.getReadACLs(new ActiveMQQueue("USERS.FOO.BAR")); - assertEquals("set size: " + readACLs, 1, readACLs.size()); - assertTrue("Contains users group", readACLs.contains(ADMINS)); - assertTrue("Contains users group", readACLs.contains(USERS)); - - Set writeAcls = map.getWriteACLs(new ActiveMQQueue("USERS.FOO.BAR")); - assertEquals("set size: " + writeAcls, 1, writeAcls.size()); - assertTrue("Contains users group", writeAcls.contains(ADMINS)); - assertTrue("Contains users group", writeAcls.contains(USERS)); - - Set adminAcls = map.getAdminACLs(new ActiveMQQueue("USERS.FOO.BAR")); - assertEquals("set size: " + adminAcls, 1, adminAcls.size()); - assertTrue("Contains users group", adminAcls.contains(ADMINS)); - assertFalse("Contains users group", adminAcls.contains(USERS)); - - Set tempAdminACLs = map.getTempDestinationAdminACLs(); - assertEquals("set size: " + tempAdminACLs, 1, tempAdminACLs.size()); - assertTrue("Contains users group", tempAdminACLs.contains(TEMP_DESTINATION_ADMINS)); - } - - protected AuthorizationMap createWildcardAuthorizationMap() { - DefaultAuthorizationMap answer = new DefaultAuthorizationMap(); - - List entries = new ArrayList<>(); - - AuthorizationEntry entry = new AuthorizationEntry(); - entry.setQueue(">"); - try { - entry.setRead("*"); - entry.setWrite("*"); - entry.setAdmin("admins"); - } catch (Exception e) { - fail(e.toString()); - } - - entries.add(entry); - - answer.setAuthorizationEntries(entries); - - TempDestinationAuthorizationEntry tEntry = new TempDestinationAuthorizationEntry(); - try { - tEntry.setAdmin("*"); - } catch (Exception e) { - fail(e.toString()); - } - - answer.setTempDestinationAuthorizationEntry(tEntry); - - return answer; - - } - - @SuppressWarnings("rawtypes") - protected AuthorizationMap createAuthorizationMap() { - DefaultAuthorizationMap answer = new DefaultAuthorizationMap(); - - List entries = new ArrayList<>(); - - AuthorizationEntry entry = new AuthorizationEntry(); - entry.setGroupClass("org.apache.activemq.jaas.GroupPrincipal"); - entry.setQueue(">"); - try { - entry.setRead("admins"); - } catch (Exception e) { - fail(e.toString()); - } - - entries.add(entry); - // entry using default org.apache.activemq.jaas.GroupPrincipal class - entry = new AuthorizationEntry(); - entry.setQueue("USERS.>"); - try { - entry.setRead("users"); - } catch (Exception e) { - fail(e.toString()); - } - entries.add(entry); - - answer.setAuthorizationEntries(entries); - - return answer; - } - - @SuppressWarnings("rawtypes") - protected AuthorizationMap createAuthorizationMapWithTempDest() { - DefaultAuthorizationMap answer = new DefaultAuthorizationMap(); - - List entries = new ArrayList<>(); - - AuthorizationEntry entry = new AuthorizationEntry(); - entry.setQueue(">"); - try { - entry.setRead("admins"); - } catch (Exception e) { - fail(e.toString()); - } - entries.add(entry); - - entry = new AuthorizationEntry(); - entry.setQueue("USERS.>"); - try { - entry.setRead("users"); - } catch (Exception e) { - fail(e.toString()); - } - entries.add(entry); - - answer.setAuthorizationEntries(entries); - - // create entry for temporary queue - TempDestinationAuthorizationEntry tEntry = new TempDestinationAuthorizationEntry(); - try { - tEntry.setAdmin("tempDestAdmins"); - } catch (Exception e) { - fail(e.toString()); - } - - answer.setTempDestinationAuthorizationEntry(tEntry); - - return answer; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleLegacyOpenLDAPTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleLegacyOpenLDAPTest.java deleted file mode 100644 index 41ae03d891..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleLegacyOpenLDAPTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.security; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.directory.api.ldap.model.exception.LdapException; -import org.apache.directory.api.ldap.model.name.Dn; -import org.apache.directory.ldap.client.api.LdapConnection; -import org.apache.directory.ldap.client.api.LdapNetworkConnection; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - -/** - * Test of the {@link SimpleCachedLDAPAuthorizationMap} that tests against a basic OpenLDAP instance. - * Disabled by default because it requires external setup to provide the OpenLDAP instance. - * - * To enable, you need an OpenLDAP with a minimum of the following in the slapd.conf file: - * - * suffix "dc=apache,dc=org" - * rootdn "cn=Manager,dc=apache,dc=org" - * rootpw {SSHA}+Rx8kj98q3FlK5rUkT2hAtMP5v2ImQ82 - * - * If you wish to use different settings or don't use the default port, change the constants - * below for your environment. - */ -@Ignore -public class CachedLDAPAuthorizationModuleLegacyOpenLDAPTest extends AbstractCachedLDAPAuthorizationMapLegacyTest { - - protected static final String LDAP_USER = "cn=Manager,dc=apache,dc=org"; - protected static final String LDAP_PASS = "password"; - protected static final String LDAP_HOST = "localhost"; - protected static final int LDAP_PORT = 389; - - @Before - @Override - public void setup() throws Exception { - - super.setup(); - - cleanAndLoad("dc=apache,dc=org", "org/apache/activemq/security/activemq-openldap-legacy.ldif", LDAP_HOST, LDAP_PORT, LDAP_USER, LDAP_PASS, map.open()); - } - - @Override - @Test - public void testRenameDestination() throws Exception { - // Subtree rename not implemented by OpenLDAP. - } - - @Override - protected SimpleCachedLDAPAuthorizationMap createMap() { - SimpleCachedLDAPAuthorizationMap newMap = super.createMap(); - newMap.setConnectionURL("ldap://" + LDAP_HOST + ":" + String.valueOf(LDAP_PORT)); - newMap.setConnectionUsername(LDAP_USER); - newMap.setConnectionPassword(LDAP_PASS); - // Persistent search is not supported in OpenLDAP - newMap.setRefreshInterval(10); - newMap.setQueueSearchBase("ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"); - newMap.setTopicSearchBase("ou=Topic,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"); - newMap.setTempSearchBase("ou=Temp,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"); - return newMap; - } - - @Override - protected InputStream getAddLdif() { - return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-openldap-legacy-add.ldif"); - } - - @Override - protected InputStream getRemoveLdif() { - return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-openldap-legacy-delete.ldif"); - } - - @Override - protected String getQueueBaseDn() { - return "ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"; - } - - @Override - protected LdapConnection getLdapConnection() throws LdapException, IOException { - LdapConnection connection = new LdapNetworkConnection(LDAP_HOST, LDAP_PORT); - connection.bind(new Dn(LDAP_USER), LDAP_PASS); - return connection; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleLegacyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleLegacyTest.java deleted file mode 100644 index 16c830b114..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleLegacyTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.security; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.directory.api.ldap.model.exception.LdapException; -import org.apache.directory.api.ldap.model.name.Dn; -import org.apache.directory.ldap.client.api.LdapConnection; -import org.apache.directory.ldap.client.api.LdapNetworkConnection; -import org.apache.directory.server.annotations.CreateLdapServer; -import org.apache.directory.server.annotations.CreateTransport; -import org.apache.directory.server.core.annotations.ApplyLdifFiles; -import org.apache.directory.server.core.integ.FrameworkRunner; -import org.junit.runner.RunWith; - -@RunWith(FrameworkRunner.class) -@CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP")}) -@ApplyLdifFiles( - "org/apache/activemq/security/activemq-apacheds-legacy.ldif") -public class CachedLDAPAuthorizationModuleLegacyTest extends AbstractCachedLDAPAuthorizationMapLegacyTest { - - @Override - protected SimpleCachedLDAPAuthorizationMap createMap() { - SimpleCachedLDAPAuthorizationMap map = super.createMap(); - map.setConnectionURL("ldap://localhost:" + getLdapServer().getPort()); - return map; - } - - @Override - protected InputStream getAddLdif() { - return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-apacheds-legacy-add.ldif"); - } - - @Override - protected InputStream getRemoveLdif() { - return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-apacheds-legacy-delete.ldif"); - } - - @Override - protected String getQueueBaseDn() { - return "ou=Queue,ou=Destination,ou=ActiveMQ,ou=system"; - } - - @Override - protected LdapConnection getLdapConnection() throws LdapException, IOException { - LdapConnection connection = new LdapNetworkConnection("localhost", getLdapServer().getPort()); - connection.bind(new Dn("uid=admin,ou=system"), "secret"); - return connection; - } -} - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleOpenLDAPTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleOpenLDAPTest.java deleted file mode 100644 index d19a220f6a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleOpenLDAPTest.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.activemq.security; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.directory.api.ldap.model.exception.LdapException; -import org.apache.directory.api.ldap.model.name.Dn; -import org.apache.directory.ldap.client.api.LdapConnection; -import org.apache.directory.ldap.client.api.LdapNetworkConnection; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - -/** - * Test of the {@link SimpleCachedLDAPAuthorizationMap} that tests against a basic OpenLDAP instance. - * Disabled by default because it requires external setup to provide the OpenLDAP instance. - * - * To enable, you need an OpenLDAP with a minimum of the following in the slapd.conf file: - * - * suffix "dc=apache,dc=org" - * rootdn "cn=Manager,dc=apache,dc=org" - * rootpw {SSHA}+Rx8kj98q3FlK5rUkT2hAtMP5v2ImQ82 - * - * If you wish to use different settings or don't use the default port, change the constants - * below for your environment. - */ -@Ignore -public class CachedLDAPAuthorizationModuleOpenLDAPTest extends AbstractCachedLDAPAuthorizationModuleTest { - - protected static final String LDAP_USER = "cn=Manager,dc=apache,dc=org"; - protected static final String LDAP_PASS = "password"; - protected static final String LDAP_HOST = "localhost"; - protected static final int LDAP_PORT = 389; - - @Before - @Override - public void setup() throws Exception { - - super.setup(); - - cleanAndLoad("dc=apache,dc=org", "org/apache/activemq/security/activemq-openldap.ldif", LDAP_HOST, LDAP_PORT, LDAP_USER, LDAP_PASS, map.open()); - } - - @Override - @Test - public void testRenameDestination() throws Exception { - // Subtree rename not implemented by OpenLDAP. - } - - @Override - protected SimpleCachedLDAPAuthorizationMap createMap() { - SimpleCachedLDAPAuthorizationMap newMap = super.createMap(); - newMap.setConnectionURL("ldap://" + LDAP_HOST + ":" + String.valueOf(LDAP_PORT)); - newMap.setConnectionUsername(LDAP_USER); - newMap.setConnectionPassword(LDAP_PASS); - // Persistent search is not supported in OpenLDAP - newMap.setRefreshInterval(10); - newMap.setQueueSearchBase("ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"); - newMap.setTopicSearchBase("ou=Topic,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"); - newMap.setTempSearchBase("ou=Temp,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"); - return newMap; - } - - @Override - protected InputStream getAddLdif() { - return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-openldap-add.ldif"); - } - - @Override - protected InputStream getRemoveLdif() { - return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-openldap-delete.ldif"); - } - - @Override - protected String getMemberAttributeValueForModifyRequest() { - return "cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"; - } - - @Override - protected String getQueueBaseDn() { - return "ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org"; - } - - @Override - protected LdapConnection getLdapConnection() throws LdapException, IOException { - LdapConnection connection = new LdapNetworkConnection(LDAP_HOST, LDAP_PORT); - connection.bind(new Dn(LDAP_USER), LDAP_PASS); - return connection; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleTest.java deleted file mode 100644 index fa9bd981e0..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPAuthorizationModuleTest.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.activemq.security; - -import java.io.InputStream; - -import org.apache.directory.api.ldap.model.name.Dn; -import org.apache.directory.ldap.client.api.LdapConnection; -import org.apache.directory.ldap.client.api.LdapNetworkConnection; -import org.apache.directory.server.annotations.CreateLdapServer; -import org.apache.directory.server.annotations.CreateTransport; -import org.apache.directory.server.core.annotations.ApplyLdifFiles; -import org.apache.directory.server.core.integ.FrameworkRunner; -import org.junit.runner.RunWith; - -@RunWith(FrameworkRunner.class) -@CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP")}) -@ApplyLdifFiles( - "org/apache/activemq/security/activemq-apacheds.ldif") -public class CachedLDAPAuthorizationModuleTest extends AbstractCachedLDAPAuthorizationModuleTest { - - @Override - protected SimpleCachedLDAPAuthorizationMap createMap() { - SimpleCachedLDAPAuthorizationMap map = super.createMap(); - map.setConnectionURL("ldap://localhost:" + getLdapServer().getPort()); - return map; - } - - @Override - protected InputStream getAddLdif() { - return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-apacheds-add.ldif"); - } - - @Override - protected InputStream getRemoveLdif() { - return getClass().getClassLoader().getResourceAsStream("org/apache/activemq/security/activemq-apacheds-delete.ldif"); - } - - @Override - protected String getMemberAttributeValueForModifyRequest() { - return "cn=users,ou=Group,ou=ActiveMQ,ou=system"; - } - - @Override - protected String getQueueBaseDn() { - return "ou=Queue,ou=Destination,ou=ActiveMQ,ou=system"; - } - - @Override - protected LdapConnection getLdapConnection() throws Exception { - LdapConnection connection = new LdapNetworkConnection("localhost", getLdapServer().getPort()); - connection.bind(new Dn("uid=admin,ou=system"), "secret"); - return connection; - } -} - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPSecurityLegacyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPSecurityLegacyTest.java deleted file mode 100644 index eb4292dc96..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPSecurityLegacyTest.java +++ /dev/null @@ -1,133 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.security; - -import javax.jms.Connection; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.directory.server.annotations.CreateLdapServer; -import org.apache.directory.server.annotations.CreateTransport; -import org.apache.directory.server.core.annotations.ApplyLdifFiles; -import org.apache.directory.server.core.integ.AbstractLdapTestUnit; -import org.apache.directory.server.core.integ.FrameworkRunner; -import org.apache.directory.server.ldap.LdapServer; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -@RunWith(FrameworkRunner.class) -@CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP")}) -@ApplyLdifFiles( - "org/apache/activemq/security/activemq-apacheds-legacy.ldif") -public class CachedLDAPSecurityLegacyTest extends AbstractLdapTestUnit { - - public BrokerService broker; - - public static LdapServer ldapServer; - - @Before - public void setup() throws Exception { - System.setProperty("ldapPort", String.valueOf(getLdapServer().getPort())); - - broker = BrokerFactory.createBroker("xbean:org/apache/activemq/security/activemq-apacheds-legacy.xml"); - broker.start(); - broker.waitUntilStarted(); - } - - @After - public void shutdown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } - - @Test - public void testSendReceive() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection conn = factory.createQueueConnection("jdoe", "sunflower"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - Queue queue = sess.createQueue("TEST.FOO"); - - MessageProducer producer = sess.createProducer(queue); - MessageConsumer consumer = sess.createConsumer(queue); - - producer.send(sess.createTextMessage("test")); - Message msg = consumer.receive(1000); - assertNotNull(msg); - } - - @Test - public void testSendDenied() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection conn = factory.createQueueConnection("jdoe", "sunflower"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - Queue queue = sess.createQueue("ADMIN.FOO"); - - try { - sess.createProducer(queue); - fail("expect auth exception"); - } catch (JMSException expected) { - } - } - - @Test - public void testCompositeSendDenied() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection conn = factory.createQueueConnection("jdoe", "sunflower"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - Queue queue = sess.createQueue("TEST.FOO,ADMIN.FOO"); - - try { - sess.createProducer(queue); - fail("expect auth exception"); - } catch (JMSException expected) { - } - } - - @Test - public void testTempDestinations() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection conn = factory.createQueueConnection("jdoe", "sunflower"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - Queue queue = sess.createTemporaryQueue(); - - MessageProducer producer = sess.createProducer(queue); - MessageConsumer consumer = sess.createConsumer(queue); - - producer.send(sess.createTextMessage("test")); - Message msg = consumer.receive(1000); - assertNotNull(msg); - } - -} - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPSecurityTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPSecurityTest.java deleted file mode 100644 index bba3ba256a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/CachedLDAPSecurityTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.security; - -import org.apache.activemq.broker.BrokerFactory; -import org.apache.directory.server.annotations.CreateLdapServer; -import org.apache.directory.server.annotations.CreateTransport; -import org.apache.directory.server.core.annotations.ApplyLdifFiles; -import org.apache.directory.server.core.integ.FrameworkRunner; -import org.junit.Before; -import org.junit.runner.RunWith; - -@RunWith(FrameworkRunner.class) -@CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP")}) -@ApplyLdifFiles( - "org/apache/activemq/security/activemq-apacheds.ldif") -public class CachedLDAPSecurityTest extends CachedLDAPSecurityLegacyTest { - - @Before - @Override - public void setup() throws Exception { - System.setProperty("ldapPort", String.valueOf(getLdapServer().getPort())); - - broker = BrokerFactory.createBroker("xbean:org/apache/activemq/security/activemq-apacheds.xml"); - broker.start(); - broker.waitUntilStarted(); - } -} - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/DoSTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/DoSTest.java deleted file mode 100644 index aa9f193edf..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/DoSTest.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.activemq.security; - -import javax.jms.Connection; -import javax.jms.JMSException; -import java.net.URI; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.JmsTestSupport; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The configuration is set to except a maximum of 2 concurrent connections - * As the exception is deliberately ignored, the ActiveMQConnection would continue to - * attempt to connect unless the connection's transport was also stopped on an error. - *
- * As the maximum connections allowed is 2, no more connections would be allowed unless - * the transport was adequately destroyed on the broker side. - */ - -public class DoSTest extends JmsTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(DoSTest.class); - - public void testInvalidAuthentication() throws Throwable { - - // with failover reconnect, we don't expect this thread to complete - // but periodically the failure changes from ExceededMaximumConnectionsException on the broker - // side to a SecurityException. - // A failed to authenticated but idle connection (dos style) is aborted by the inactivity monitor - // since useKeepAlive=false - - final AtomicBoolean done = new AtomicBoolean(false); - Thread thread = new Thread() { - Connection connection = null; - - @Override - public void run() { - for (int i = 0; i < 1000 && !done.get(); i++) { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(); - try { - // Bad password - connection = factory.createConnection("bad", "krap"); - connection.start(); - fail("Expected exception."); - } catch (JMSException e) { - // ignore exception and don't close - e.printStackTrace(); - } - } - } - }; - - thread.start(); - - // run dos for a while - TimeUnit.SECONDS.sleep(10); - - LOG.info("trying genuine connection ..."); - // verify a valid connection can work with one of the 2 allowed connections provided it is eager! - // it could take a while as it is competing with the three other reconnect threads. - // wonder if it makes sense to serialise these reconnect attempts on an executor - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("failover:(tcp://127.0.0.1:61616)?useExponentialBackOff=false&reconnectDelay=10"); - Connection goodConnection = factory.createConnection("user", "password"); - goodConnection.start(); - goodConnection.close(); - - LOG.info("giving up on DOS"); - done.set(true); - } - - @Override - protected BrokerService createBroker() throws Exception { - return createBroker("org/apache/activemq/security/dos-broker.xml"); - } - - protected BrokerService createBroker(String uri) throws Exception { - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasCertificateAuthenticationBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasCertificateAuthenticationBrokerTest.java deleted file mode 100644 index 6ed2fda011..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasCertificateAuthenticationBrokerTest.java +++ /dev/null @@ -1,186 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.security; - -import javax.security.auth.login.AppConfigurationEntry; -import javax.security.auth.login.Configuration; -import java.security.Principal; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import junit.framework.TestCase; - -import org.apache.activemq.broker.ConnectionContext; -import org.apache.activemq.broker.StubBroker; -import org.apache.activemq.command.ConnectionInfo; -import org.apache.activemq.jaas.GroupPrincipal; -import org.apache.activemq.jaas.UserPrincipal; -import org.apache.activemq.transport.tcp.StubX509Certificate; - -public class JaasCertificateAuthenticationBrokerTest extends TestCase { - - StubBroker receiveBroker; - - JaasCertificateAuthenticationBroker authBroker; - - ConnectionContext connectionContext; - ConnectionInfo connectionInfo; - - @Override - protected void setUp() throws Exception { - receiveBroker = new StubBroker(); - - authBroker = new JaasCertificateAuthenticationBroker(receiveBroker, ""); - - connectionContext = new ConnectionContext(); - connectionInfo = new ConnectionInfo(); - - connectionInfo.setTransportContext(new StubX509Certificate[]{}); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } - - private void setConfiguration(Set userNames, Set groupNames, boolean loginShouldSucceed) { - HashMap configOptions = new HashMap<>(); - - String userNamesString; - { - Iterator iter = userNames.iterator(); - userNamesString = "" + (iter.hasNext() ? iter.next() : ""); - while (iter.hasNext()) { - userNamesString += "," + iter.next(); - } - } - - String groupNamesString = ""; - { - Iterator iter = groupNames.iterator(); - groupNamesString = "" + (iter.hasNext() ? iter.next() : ""); - while (iter.hasNext()) { - groupNamesString += "," + iter.next(); - } - } - - configOptions.put(StubLoginModule.ALLOW_LOGIN_PROPERTY, loginShouldSucceed ? "true" : "false"); - configOptions.put(StubLoginModule.USERS_PROPERTY, userNamesString); - configOptions.put(StubLoginModule.GROUPS_PROPERTY, groupNamesString); - AppConfigurationEntry configEntry = new AppConfigurationEntry("org.apache.activemq.security.StubLoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, configOptions); - - StubJaasConfiguration jaasConfig = new StubJaasConfiguration(configEntry); - - Configuration.setConfiguration(jaasConfig); - } - - public void testAddConnectionSuccess() { - String dnUserName = "dnUserName"; - - HashSet userNames = new HashSet<>(); - userNames.add(dnUserName); - - HashSet groupNames = new HashSet<>(); - groupNames.add("testGroup1"); - groupNames.add("testGroup2"); - groupNames.add("tesetGroup3"); - - setConfiguration(userNames, groupNames, true); - - try { - authBroker.addConnection(connectionContext, connectionInfo); - } catch (Exception e) { - fail("Call to addConnection failed: " + e.getMessage()); - } - - assertEquals("Number of addConnection calls to underlying Broker must match number of calls made to " + "AuthenticationBroker.", 1, receiveBroker.addConnectionData.size()); - - ConnectionContext receivedContext = receiveBroker.addConnectionData.getFirst().connectionContext; - - assertEquals("The SecurityContext's userName must be set to that of the UserPrincipal.", dnUserName, receivedContext.getSecurityContext().getUserName()); - - Set receivedPrincipals = receivedContext.getSecurityContext().getPrincipals(); - - for (Iterator iter = receivedPrincipals.iterator(); iter.hasNext(); ) { - Principal currentPrincipal = iter.next(); - - if (currentPrincipal instanceof UserPrincipal) { - if (userNames.remove(currentPrincipal.getName())) { - // Nothing, we did good. - } else { - // Found an unknown userName. - fail("Unknown UserPrincipal found"); - } - } else if (currentPrincipal instanceof GroupPrincipal) { - if (groupNames.remove(currentPrincipal.getName())) { - // Nothing, we did good. - } else { - fail("Unknown GroupPrincipal found."); - } - } else { - fail("Unexpected Principal subclass found."); - } - } - - if (!userNames.isEmpty()) { - fail("Some usernames were not added as UserPrincipals"); - } - - if (!groupNames.isEmpty()) { - fail("Some group names were not added as GroupPrincipals"); - } - } - - public void testAddConnectionFailure() { - HashSet userNames = new HashSet<>(); - - HashSet groupNames = new HashSet<>(); - groupNames.add("testGroup1"); - groupNames.add("testGroup2"); - groupNames.add("tesetGroup3"); - - setConfiguration(userNames, groupNames, false); - - boolean connectFailed = false; - try { - authBroker.addConnection(connectionContext, connectionInfo); - } catch (SecurityException e) { - connectFailed = true; - } catch (Exception e) { - fail("Failed to connect for unexpected reason: " + e.getMessage()); - } - - if (!connectFailed) { - fail("Unauthenticated connection allowed."); - } - - assertEquals("Unauthenticated connection allowed.", true, receiveBroker.addConnectionData.isEmpty()); - } - - public void testRemoveConnection() throws Exception { - connectionContext.setSecurityContext(new StubSecurityContext()); - - authBroker.removeConnection(connectionContext, connectionInfo, new Throwable()); - - assertEquals("removeConnection should clear ConnectionContext.", null, connectionContext.getSecurityContext()); - - assertEquals("Incorrect number of calls to underlying broker were made.", 1, receiveBroker.removeConnectionData.size()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasDualAuthenticationBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasDualAuthenticationBrokerTest.java deleted file mode 100644 index fe561587de..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasDualAuthenticationBrokerTest.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.activemq.security; - -import javax.net.ssl.SSLServerSocket; -import javax.security.auth.login.AppConfigurationEntry; -import javax.security.auth.login.Configuration; -import java.net.URI; -import java.security.Principal; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Set; - -import junit.framework.TestCase; - -import org.apache.activemq.broker.ConnectionContext; -import org.apache.activemq.broker.Connector; -import org.apache.activemq.broker.StubBroker; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.command.ConnectionInfo; -import org.apache.activemq.jaas.GroupPrincipal; -import org.apache.activemq.jaas.UserPrincipal; -import org.apache.activemq.transport.tcp.SslTransportServer; -import org.apache.activemq.transport.tcp.StubSSLServerSocket; -import org.apache.activemq.transport.tcp.StubSSLSocketFactory; -import org.apache.activemq.transport.tcp.StubX509Certificate; -import org.apache.activemq.transport.tcp.TcpTransportServer; - -/** - * - */ -public class JaasDualAuthenticationBrokerTest extends TestCase { - - private static final String INSECURE_GROUP = "insecureGroup"; - private static final String INSECURE_USERNAME = "insecureUserName"; - private static final String DN_GROUP = "dnGroup"; - private static final String DN_USERNAME = "dnUserName"; - - StubBroker receiveBroker; - JaasDualAuthenticationBroker authBroker; - - ConnectionContext connectionContext; - ConnectionInfo connectionInfo; - - SslTransportServer sslTransportServer; - TcpTransportServer nonSslTransportServer; - - /** - * create a dual login config, for both SSL and non-SSL connections - * using the StubLoginModule - */ - void createLoginConfig() { - HashMap sslConfigOptions = new HashMap<>(); - HashMap configOptions = new HashMap<>(); - - sslConfigOptions.put(StubLoginModule.ALLOW_LOGIN_PROPERTY, "true"); - sslConfigOptions.put(StubLoginModule.USERS_PROPERTY, DN_USERNAME); - sslConfigOptions.put(StubLoginModule.GROUPS_PROPERTY, DN_GROUP); - AppConfigurationEntry sslConfigEntry = new AppConfigurationEntry("org.apache.activemq.security.StubLoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, sslConfigOptions); - - configOptions.put(StubLoginModule.ALLOW_LOGIN_PROPERTY, "true"); - configOptions.put(StubLoginModule.USERS_PROPERTY, INSECURE_USERNAME); - configOptions.put(StubLoginModule.GROUPS_PROPERTY, INSECURE_GROUP); - AppConfigurationEntry configEntry = new AppConfigurationEntry("org.apache.activemq.security.StubLoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, configOptions); - - StubDualJaasConfiguration jaasConfig = new StubDualJaasConfiguration(configEntry, sslConfigEntry); - - Configuration.setConfiguration(jaasConfig); - } - - @Override - protected void setUp() throws Exception { - receiveBroker = new StubBroker(); - - authBroker = new JaasDualAuthenticationBroker(receiveBroker, "activemq-domain", "activemq-ssl-domain"); - - connectionContext = new ConnectionContext(); - - SSLServerSocket sslServerSocket = new StubSSLServerSocket(); - StubSSLSocketFactory socketFactory = new StubSSLSocketFactory(sslServerSocket); - - try { - sslTransportServer = new SslTransportServer(null, new URI("ssl://localhost:61616?needClientAuth=true"), socketFactory); - } catch (Exception e) { - fail("Unable to create SslTransportServer."); - } - sslTransportServer.setNeedClientAuth(true); - sslTransportServer.bind(); - - try { - nonSslTransportServer = new TcpTransportServer(null, new URI("tcp://localhost:61613"), socketFactory); - } catch (Exception e) { - fail("Unable to create TcpTransportServer."); - } - - connectionInfo = new ConnectionInfo(); - - createLoginConfig(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } - - public void testSecureConnector() { - Connector connector = new TransportConnector(sslTransportServer); - connectionContext.setConnector(connector); - connectionInfo.setTransportContext(new StubX509Certificate[]{}); - - try { - authBroker.addConnection(connectionContext, connectionInfo); - } catch (Exception e) { - fail("Call to addConnection failed: " + e.getMessage()); - } - - assertEquals("Number of addConnection calls to underlying Broker must match number of calls made to " + "AuthenticationBroker.", 1, receiveBroker.addConnectionData.size()); - - ConnectionContext receivedContext = receiveBroker.addConnectionData.getFirst().connectionContext; - - assertEquals("The SecurityContext's userName must be set to that of the UserPrincipal.", DN_USERNAME, receivedContext.getSecurityContext().getUserName()); - - Set receivedPrincipals = receivedContext.getSecurityContext().getPrincipals(); - - assertEquals("2 Principals received", 2, receivedPrincipals.size()); - - for (Iterator iter = receivedPrincipals.iterator(); iter.hasNext(); ) { - Principal currentPrincipal = iter.next(); - - if (currentPrincipal instanceof UserPrincipal) { - assertEquals("UserPrincipal is '" + DN_USERNAME + "'", DN_USERNAME, currentPrincipal.getName()); - } else if (currentPrincipal instanceof GroupPrincipal) { - assertEquals("GroupPrincipal is '" + DN_GROUP + "'", DN_GROUP, currentPrincipal.getName()); - } else { - fail("Unexpected Principal subclass found."); - } - } - - try { - authBroker.removeConnection(connectionContext, connectionInfo, null); - } catch (Exception e) { - fail("Call to removeConnection failed: " + e.getMessage()); - } - assertEquals("Number of removeConnection calls to underlying Broker must match number of calls made to " + "AuthenticationBroker.", 1, receiveBroker.removeConnectionData.size()); - } - - public void testInsecureConnector() { - Connector connector = new TransportConnector(nonSslTransportServer); - connectionContext.setConnector(connector); - connectionInfo.setUserName(INSECURE_USERNAME); - - try { - authBroker.addConnection(connectionContext, connectionInfo); - } catch (Exception e) { - fail("Call to addConnection failed: " + e.getMessage()); - } - - assertEquals("Number of addConnection calls to underlying Broker must match number of calls made to " + "AuthenticationBroker.", 1, receiveBroker.addConnectionData.size()); - - ConnectionContext receivedContext = receiveBroker.addConnectionData.getFirst().connectionContext; - - assertEquals("The SecurityContext's userName must be set to that of the UserPrincipal.", INSECURE_USERNAME, receivedContext.getSecurityContext().getUserName()); - - Set receivedPrincipals = receivedContext.getSecurityContext().getPrincipals(); - - assertEquals("2 Principals received", 2, receivedPrincipals.size()); - for (Iterator iter = receivedPrincipals.iterator(); iter.hasNext(); ) { - Principal currentPrincipal = iter.next(); - - if (currentPrincipal instanceof UserPrincipal) { - assertEquals("UserPrincipal is '" + INSECURE_USERNAME + "'", INSECURE_USERNAME, currentPrincipal.getName()); - } else if (currentPrincipal instanceof GroupPrincipal) { - assertEquals("GroupPrincipal is '" + INSECURE_GROUP + "'", INSECURE_GROUP, currentPrincipal.getName()); - } else { - fail("Unexpected Principal subclass found."); - } - } - - try { - authBroker.removeConnection(connectionContext, connectionInfo, null); - } catch (Exception e) { - fail("Call to removeConnection failed: " + e.getMessage()); - } - assertEquals("Number of removeConnection calls to underlying Broker must match number of calls made to " + "AuthenticationBroker.", 1, receiveBroker.removeConnectionData.size()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasNetworkTest.java deleted file mode 100644 index dcdd32ae08..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/JaasNetworkTest.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.activemq.security; - -import javax.jms.Connection; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.net.URI; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQQueue; - -public class JaasNetworkTest extends TestCase { - - BrokerService broker1; - BrokerService broker2; - - @Override - public void setUp() throws Exception { - System.setProperty("java.security.auth.login.config", "src/test/resources/login.config"); - broker1 = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/security/broker1.xml")); - broker2 = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/security/broker2.xml")); - broker1.waitUntilStarted(); - broker2.waitUntilStarted(); - Thread.sleep(2000); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - broker1.stop(); - broker1.waitUntilStopped(); - broker2.stop(); - broker2.waitUntilStopped(); - } - - public void testNetwork() throws Exception { - - System.setProperty("javax.net.ssl.trustStore", "src/test/resources/org/apache/activemq/security/client.ts"); - System.setProperty("javax.net.ssl.trustStorePassword", "password"); - System.setProperty("javax.net.ssl.trustStoreType", "jks"); - System.setProperty("javax.net.ssl.keyStore", "src/test/resources/org/apache/activemq/security/client.ks"); - System.setProperty("javax.net.ssl.keyStorePassword", "password"); - System.setProperty("javax.net.ssl.keyStoreType", "jks"); - - ActiveMQConnectionFactory producerFactory = new ActiveMQConnectionFactory("ssl://localhost:61617"); - Connection producerConn = producerFactory.createConnection(); - Session producerSess = producerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = producerSess.createProducer(new ActiveMQQueue("test")); - producerConn.start(); - TextMessage sentMessage = producerSess.createTextMessage("test"); - producer.send(sentMessage); - - ActiveMQConnectionFactory consumerFactory = new ActiveMQConnectionFactory("ssl://localhost:61618"); - Connection consumerConn = consumerFactory.createConnection(); - Session consumerSess = consumerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumerConn.start(); - MessageConsumer consumer = consumerSess.createConsumer(new ActiveMQQueue("test")); - TextMessage receivedMessage = (TextMessage) consumer.receive(100); - assertEquals(sentMessage, receivedMessage); - - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPAuthenticationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPAuthenticationTest.java deleted file mode 100644 index e8f5dfe4fc..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPAuthenticationTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.security; - -import javax.jms.Connection; -import javax.jms.Session; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.directory.server.annotations.CreateLdapServer; -import org.apache.directory.server.annotations.CreateTransport; -import org.apache.directory.server.core.annotations.ApplyLdifFiles; -import org.apache.directory.server.core.integ.AbstractLdapTestUnit; -import org.apache.directory.server.core.integ.FrameworkRunner; -import org.apache.directory.server.ldap.LdapServer; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import static org.junit.Assert.fail; - -@RunWith(FrameworkRunner.class) -@CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP", port = 1024)}) -@ApplyLdifFiles( - "org/apache/activemq/security/activemq.ldif") -public class LDAPAuthenticationTest extends AbstractLdapTestUnit { - - public BrokerService broker; - - public static LdapServer ldapServer; - - @Before - public void setup() throws Exception { - System.setProperty("ldapPort", String.valueOf(getLdapServer().getPort())); - - broker = BrokerFactory.createBroker("xbean:org/apache/activemq/security/activemq-ldap-auth.xml"); - broker.start(); - broker.waitUntilStarted(); - } - - @After - public void shutdown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } - - @Test - public void testWildcard() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); - Connection conn = factory.createQueueConnection("*", "sunflower"); - try { - conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - } catch (Exception e) { - e.printStackTrace(); - return; - } - fail("Should have failed connecting"); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPAuthorizationMap.properties b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPAuthorizationMap.properties deleted file mode 100644 index fc7b13bc73..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPAuthorizationMap.properties +++ /dev/null @@ -1,33 +0,0 @@ -## --------------------------------------------------------------------------- -## Licensed to the Apache Software Foundation (ASF) under one or more -## contributor license agreements. See the NOTICE file distributed with -## this work for additional information regarding copyright ownership. -## The ASF licenses this file to You under the Apache License, Version 2.0 -## (the "License"); you may not use this file except in compliance with -## the License. You may obtain a copy of the License at -## -## http://www.apache.org/licenses/LICENSE-2.0 -## -## Unless required by applicable law or agreed to in writing, software -## distributed under the License is distributed on an "AS IS" BASIS, -## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -## See the License for the specific language governing permissions and -## limitations under the License. -## --------------------------------------------------------------------------- - -initialContextFactory = com.sun.jndi.ldap.LdapCtxFactory -connectionURL = ldap://localhost:10389 -authentication = simple -connectionUsername = uid=admin,ou=system -connectionPassword = secret -connectionProtocol = s -topicSearchMatching = uid={0},ou=topics,ou=destinations,o=ActiveMQ,dc=example,dc=com -topicSearchSubtree = true -queueSearchMatching = uid={0},ou=queues,ou=destinations,o=ActiveMQ,dc=example,dc=com -queueSearchSubtree = true -adminBase = (cn=admin) -adminAttribute = uniqueMember -readBase = (cn=read) -readAttribute = uniqueMember -writeBAse = (cn=write) -writeAttribute = uniqueMember diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPAuthorizationMapTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPAuthorizationMapTest.java deleted file mode 100644 index 6a674f71ea..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPAuthorizationMapTest.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.activemq.security; - -import javax.naming.NameClassPair; -import javax.naming.NamingEnumeration; -import javax.naming.directory.DirContext; -import java.text.MessageFormat; -import java.util.HashSet; -import java.util.Set; - -import org.apache.activemq.advisory.AdvisorySupport; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.jaas.GroupPrincipal; -import org.apache.directory.server.annotations.CreateLdapServer; -import org.apache.directory.server.annotations.CreateTransport; -import org.apache.directory.server.core.annotations.ApplyLdifFiles; -import org.apache.directory.server.core.integ.AbstractLdapTestUnit; -import org.apache.directory.server.core.integ.FrameworkRunner; -import org.apache.directory.server.ldap.LdapServer; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -/** - * This test assumes setup like in file 'AMQauth.ldif'. Contents of this file is attached below in comments. - * - * @author ngcutura - */ -@RunWith(FrameworkRunner.class) -@CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP")}) -@ApplyLdifFiles("org/apache/activemq/security/AMQauth.ldif") -public class LDAPAuthorizationMapTest extends AbstractLdapTestUnit { - - private static LDAPAuthorizationMap authMap; - - public static LdapServer ldapServer; - - @Before - public void setup() throws Exception { - authMap = new LDAPAuthorizationMap(); - authMap.setConnectionURL("ldap://localhost:" + getLdapServer().getPort()); - authMap.setTopicSearchMatchingFormat(new MessageFormat("uid={0},ou=topics,ou=destinations,o=ActiveMQ,ou=system")); - authMap.setQueueSearchMatchingFormat(new MessageFormat("uid={0},ou=queues,ou=destinations,o=ActiveMQ,ou=system")); - authMap.setAdvisorySearchBase("uid=ActiveMQ.Advisory,ou=topics,ou=destinations,o=ActiveMQ,ou=system"); - authMap.setTempSearchBase("uid=ActiveMQ.Temp,ou=topics,ou=destinations,o=ActiveMQ,ou=system"); - } - - @Test - public void testOpen() throws Exception { - DirContext ctx = authMap.open(); - HashSet set = new HashSet<>(); - NamingEnumeration list = ctx.list("ou=destinations,o=ActiveMQ,ou=system"); - while (list.hasMore()) { - NameClassPair ncp = list.next(); - set.add(ncp.getName()); - } - assertTrue(set.contains("ou=topics")); - assertTrue(set.contains("ou=queues")); - } - - /* - * Test method for 'org.apache.activemq.security.LDAPAuthorizationMap.getAdminACLs(ActiveMQDestination)' - */ - @Test - public void testGetAdminACLs() { - ActiveMQDestination q1 = new ActiveMQQueue("queue1"); - Set aclsq1 = authMap.getAdminACLs(q1); - assertEquals(1, aclsq1.size()); - assertTrue(aclsq1.contains(new GroupPrincipal("role1"))); - - ActiveMQDestination t1 = new ActiveMQTopic("topic1"); - Set aclst1 = authMap.getAdminACLs(t1); - assertEquals(1, aclst1.size()); - assertTrue(aclst1.contains(new GroupPrincipal("role1"))); - } - - /* - * Test method for 'org.apache.activemq.security.LDAPAuthorizationMap.getReadACLs(ActiveMQDestination)' - */ - @Test - public void testGetReadACLs() { - ActiveMQDestination q1 = new ActiveMQQueue("queue1"); - Set aclsq1 = authMap.getReadACLs(q1); - assertEquals(1, aclsq1.size()); - assertTrue(aclsq1.contains(new GroupPrincipal("role1"))); - - ActiveMQDestination t1 = new ActiveMQTopic("topic1"); - Set aclst1 = authMap.getReadACLs(t1); - assertEquals(1, aclst1.size()); - assertTrue(aclst1.contains(new GroupPrincipal("role2"))); - } - - /* - * Test method for 'org.apache.activemq.security.LDAPAuthorizationMap.getWriteACLs(ActiveMQDestination)' - */ - @Test - public void testGetWriteACLs() { - ActiveMQDestination q1 = new ActiveMQQueue("queue1"); - Set aclsq1 = authMap.getWriteACLs(q1); - assertEquals(2, aclsq1.size()); - assertTrue(aclsq1.contains(new GroupPrincipal("role1"))); - assertTrue(aclsq1.contains(new GroupPrincipal("role2"))); - - ActiveMQDestination t1 = new ActiveMQTopic("topic1"); - Set aclst1 = authMap.getWriteACLs(t1); - assertEquals(1, aclst1.size()); - assertTrue(aclst1.contains(new GroupPrincipal("role3"))); - } - - @Test - public void testComposite() { - ActiveMQDestination q1 = new ActiveMQQueue("queue1,topic://topic1"); - Set aclsq1 = authMap.getWriteACLs(q1); - assertEquals(0, aclsq1.size()); - } - - @Test - public void testAdvisory() { - ActiveMQDestination dest = AdvisorySupport.getConnectionAdvisoryTopic(); - Set acls = authMap.getWriteACLs(dest); - - assertEquals(1, acls.size()); - assertTrue(acls.contains(new GroupPrincipal("role3"))); - } - - @Test - public void testTemp() { - Set acls = authMap.getTempDestinationAdminACLs(); - - assertEquals(1, acls.size()); - assertTrue(acls.contains(new GroupPrincipal("role1"))); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPSecurityTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPSecurityTest.java deleted file mode 100644 index d5c4472a5a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/LDAPSecurityTest.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.activemq.security; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.directory.server.annotations.CreateLdapServer; -import org.apache.directory.server.annotations.CreateTransport; -import org.apache.directory.server.core.annotations.ApplyLdifFiles; -import org.apache.directory.server.core.integ.AbstractLdapTestUnit; -import org.apache.directory.server.core.integ.FrameworkRunner; -import org.apache.directory.server.ldap.LdapServer; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -@RunWith(FrameworkRunner.class) -@CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP", port = 1024)}) -@ApplyLdifFiles( - "org/apache/activemq/security/activemq.ldif") -public class LDAPSecurityTest extends AbstractLdapTestUnit { - - public BrokerService broker; - - public static LdapServer ldapServer; - - @Before - public void setup() throws Exception { - System.setProperty("ldapPort", String.valueOf(getLdapServer().getPort())); - - broker = BrokerFactory.createBroker("xbean:org/apache/activemq/security/activemq-ldap.xml"); - broker.start(); - broker.waitUntilStarted(); - } - - @After - public void shutdown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } - - @Test - public void testSendReceive() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); - Connection conn = factory.createQueueConnection("jdoe", "sunflower"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - Destination queue = sess.createQueue("TEST.FOO"); - - MessageProducer producer = sess.createProducer(queue); - MessageConsumer consumer = sess.createConsumer(queue); - - producer.send(sess.createTextMessage("test")); - Message msg = consumer.receive(1000); - assertNotNull(msg); - } - - @Test - public void testSendTopic() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); - Connection conn = factory.createQueueConnection("jdoe", "sunflower"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - Destination topic = sess.createTopic("TEST.BAR"); - - MessageProducer producer = sess.createProducer(topic); - MessageConsumer consumer = sess.createConsumer(topic); - - producer.send(sess.createTextMessage("test")); - Message msg = consumer.receive(1000); - assertNotNull(msg); - } - - @Test - public void testSendDenied() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); - Connection conn = factory.createQueueConnection("jdoe", "sunflower"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - Queue queue = sess.createQueue("ADMIN.FOO"); - - try { - MessageProducer producer = sess.createProducer(queue); - producer.send(sess.createTextMessage("test")); - fail("expect auth exception"); - } catch (JMSException expected) { - } - } - - @Test - public void testCompositeSendDenied() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); - Connection conn = factory.createQueueConnection("jdoe", "sunflower"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - Queue queue = sess.createQueue("TEST.FOO,ADMIN.FOO"); - - try { - MessageProducer producer = sess.createProducer(queue); - producer.send(sess.createTextMessage("test")); - fail("expect auth exception"); - } catch (JMSException expected) { - } - } - - @Test - public void testTempDestinations() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); - Connection conn = factory.createQueueConnection("jdoe", "sunflower"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - Queue queue = sess.createTemporaryQueue(); - - MessageProducer producer = sess.createProducer(queue); - MessageConsumer consumer = sess.createConsumer(queue); - - producer.send(sess.createTextMessage("test")); - Message msg = consumer.receive(1000); - assertNotNull(msg); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SecurityJMXTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SecurityJMXTest.java deleted file mode 100644 index feed55b635..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SecurityJMXTest.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.activemq.security; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.QueueBrowser; -import javax.jms.Session; -import javax.management.MBeanServerConnection; -import javax.management.MBeanServerInvocationHandler; -import javax.management.ObjectName; -import javax.management.remote.JMXConnector; -import javax.management.remote.JMXConnectorFactory; -import javax.management.remote.JMXServiceURL; -import java.net.URI; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.jmx.QueueViewMBean; -import org.apache.activemq.command.ActiveMQQueue; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SecurityJMXTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(SimpleAuthenticationPluginTest.class); - private BrokerService broker; - - @Override - public void setUp() throws Exception { - broker = createBroker(); - broker.waitUntilStarted(); - } - - @Override - public void tearDown() throws Exception { - broker.stop(); - } - - public void testMoveMessages() throws Exception { - JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1199/jmxrmi"); - JMXConnector connector = JMXConnectorFactory.connect(url, null); - connector.connect(); - MBeanServerConnection connection = connector.getMBeanServerConnection(); - ObjectName name = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost," + "destinationType=Queue,destinationName=TEST.Q"); - QueueViewMBean queueMbean = MBeanServerInvocationHandler.newProxyInstance(connection, name, QueueViewMBean.class, true); - String msgId = queueMbean.sendTextMessage("test", "system", "manager"); - queueMbean.moveMessageTo(msgId, "TEST1.Q"); - } - - public void testBrowseExpiredMessages() throws Exception { - JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1199/jmxrmi"); - JMXConnector connector = JMXConnectorFactory.connect(url, null); - connector.connect(); - MBeanServerConnection connection = connector.getMBeanServerConnection(); - ObjectName name = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost," + "destinationType=Queue,destinationName=TEST.Q"); - QueueViewMBean queueMbean = MBeanServerInvocationHandler.newProxyInstance(connection, name, QueueViewMBean.class, true); - HashMap headers = new HashMap<>(); - headers.put("timeToLive", Long.toString(2000)); - headers.put("JMSDeliveryMode", Integer.toString(DeliveryMode.PERSISTENT)); - queueMbean.sendTextMessage(headers, "test", "system", "manager"); - // allow message to expire on the queue - TimeUnit.SECONDS.sleep(4); - - Connection c = new ActiveMQConnectionFactory("vm://localhost").createConnection("system", "manager"); - c.start(); - - // browser consumer will force expiration check on addConsumer - QueueBrowser browser = c.createSession(false, Session.AUTO_ACKNOWLEDGE).createBrowser(new ActiveMQQueue("TEST.Q")); - assertTrue("no message in the q", !browser.getEnumeration().hasMoreElements()); - - // verify dlq got the message, no security exception as brokers context is now used - browser = c.createSession(false, Session.AUTO_ACKNOWLEDGE).createBrowser(new ActiveMQQueue("ActiveMQ.DLQ")); - assertTrue("one message in the dlq", browser.getEnumeration().hasMoreElements()); - } - - protected BrokerService createBroker() throws Exception { - return createBroker("org/apache/activemq/security/simple-auth-broker.xml"); - } - - protected BrokerService createBroker(String uri) throws Exception { - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SecurityTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SecurityTestSupport.java deleted file mode 100644 index f773738258..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SecurityTestSupport.java +++ /dev/null @@ -1,263 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.security; - -import javax.jms.Connection; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.Session; -import javax.jms.TextMessage; - -import org.apache.activemq.CombinationTestSupport; -import org.apache.activemq.JmsTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQMessage; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; - -/** - * - */ -public class SecurityTestSupport extends JmsTestSupport { - - public ActiveMQDestination destination; - - /** - * Overrides to set the JMSXUserID flag to true. - */ - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - broker.setPopulateJMSXUserID(true); - return broker; - } - - public void testUserReceiveFails() throws JMSException { - doReceive(true); - } - - public void testInvalidAuthentication() throws JMSException { - try { - // No user id - Connection c = factory.createConnection(); - connections.add(c); - c.start(); - fail("Expected exception."); - } catch (JMSException e) { - } - - try { - // Bad password - Connection c = factory.createConnection("user", "krap"); - connections.add(c); - c.start(); - fail("Expected exception."); - } catch (JMSException e) { - } - - try { - // Bad userid - Connection c = factory.createConnection("userkrap", null); - connections.add(c); - c.start(); - fail("Expected exception."); - } catch (JMSException e) { - } - } - - public void testUserReceiveSucceeds() throws JMSException { - Message m = doReceive(false); - assertEquals("system", ((ActiveMQMessage) m).getUserID()); - assertEquals("system", m.getStringProperty("JMSXUserID")); - } - - public void testGuestReceiveSucceeds() throws JMSException { - doReceive(false); - } - - public void testGuestReceiveFails() throws JMSException { - doReceive(true); - } - - public void testUserSendSucceeds() throws JMSException { - Message m = doSend(false); - assertEquals("user", ((ActiveMQMessage) m).getUserID()); - assertEquals("user", m.getStringProperty("JMSXUserID")); - } - - public void testUserSendFails() throws JMSException { - doSend(true); - } - - public void testGuestSendFails() throws JMSException { - doSend(true); - } - - public void testGuestSendSucceeds() throws JMSException { - doSend(false); - } - - /** - * @throws JMSException - */ - public Message doSend(boolean fail) throws JMSException { - - Connection adminConnection = factory.createConnection("system", "manager"); - connections.add(adminConnection); - - adminConnection.start(); - Session adminSession = adminConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = adminSession.createConsumer(destination); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - try { - sendMessages(session, destination, 1); - } catch (JMSException e) { - // If test is expected to fail, the cause must only be a - // SecurityException - // otherwise rethrow the exception - if (!fail || !(e.getCause() instanceof SecurityException)) { - throw e; - } - } - - Message m = consumer.receive(1000); - if (fail) { - assertNull(m); - } else { - assertNotNull(m); - assertEquals("0", ((TextMessage) m).getText()); - assertNull(consumer.receiveNoWait()); - } - return m; - } - - /** - * @throws JMSException - */ - public Message doReceive(boolean fail) throws JMSException { - - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = null; - try { - consumer = session.createConsumer(destination); - if (fail) { - fail("Expected failure due to security constraint."); - } - } catch (JMSException e) { - if (fail && e.getCause() instanceof SecurityException) { - return null; - } - throw e; - } - - Connection adminConnection = factory.createConnection("system", "manager"); - connections.add(adminConnection); - Session adminSession = adminConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - sendMessages(adminSession, destination, 1); - - Message m = consumer.receive(1000); - assertNotNull(m); - assertEquals("0", ((TextMessage) m).getText()); - assertNull(consumer.receiveNoWait()); - return m; - - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestUserReceiveFails() { - addCombinationValues("userName", new Object[]{"user"}); - addCombinationValues("password", new Object[]{"password"}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("USERS.BY_PASS, TEST"), new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("GUEST.BAR"), new ActiveMQTopic("GUEST.BAR")}); - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestInvalidAuthentication() { - addCombinationValues("userName", new Object[]{"user"}); - addCombinationValues("password", new Object[]{"password"}); - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestUserReceiveSucceeds() { - addCombinationValues("userName", new Object[]{"user"}); - addCombinationValues("password", new Object[]{"password"}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("USERS.FOO"), new ActiveMQTopic("USERS.FOO")}); - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestGuestReceiveSucceeds() { - addCombinationValues("userName", new Object[]{"guest"}); - addCombinationValues("password", new Object[]{"password"}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("GUEST.BAR"), new ActiveMQTopic("GUEST.BAR")}); - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestGuestReceiveFails() { - addCombinationValues("userName", new Object[]{"guest"}); - addCombinationValues("password", new Object[]{"password"}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("GUESTS.BY_PASS,TEST"), new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("USERS.FOO"), new ActiveMQTopic("USERS.FOO")}); - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestUserSendSucceeds() { - addCombinationValues("userName", new Object[]{"user"}); - addCombinationValues("password", new Object[]{"password"}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("USERS.FOO"), new ActiveMQQueue("GUEST.BAR"), new ActiveMQTopic("USERS.FOO"), new ActiveMQTopic("GUEST.BAR")}); - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestUserSendFails() { - addCombinationValues("userName", new Object[]{"user"}); - addCombinationValues("password", new Object[]{"password"}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("USERS.BY_PASS,TEST"), new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST")}); - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestGuestSendFails() { - addCombinationValues("userName", new Object[]{"guest"}); - addCombinationValues("password", new Object[]{"password"}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("GUESTS.BY_PASS,TEST"), new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("USERS.FOO"), new ActiveMQTopic("USERS.FOO")}); - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestGuestSendSucceeds() { - addCombinationValues("userName", new Object[]{"guest"}); - addCombinationValues("password", new Object[]{"password"}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("GUEST.BAR"), new ActiveMQTopic("GUEST.BAR")}); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAnonymousPluginTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAnonymousPluginTest.java deleted file mode 100644 index dfa54908b0..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAnonymousPluginTest.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.activemq.security; - -import javax.jms.Connection; -import javax.jms.JMSException; - -import junit.framework.Test; - -import org.apache.activemq.CombinationTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; - -public class SimpleAnonymousPluginTest extends SimpleAuthenticationPluginTest { - - public static Test suite() { - return suite(SimpleAnonymousPluginTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - @Override - protected BrokerService createBroker() throws Exception { - return createBroker("org/apache/activemq/security/simple-anonymous-broker.xml"); - } - - @Override - public void testInvalidAuthentication() throws JMSException { - - try { - // Bad password - Connection c = factory.createConnection("user", "krap"); - connections.add(c); - c.start(); - fail("Expected exception."); - } catch (JMSException e) { - } - - try { - // Bad userid - Connection c = factory.createConnection("userkrap", null); - connections.add(c); - c.start(); - fail("Expected exception."); - } catch (JMSException e) { - } - } - - public void testAnonymousReceiveSucceeds() throws JMSException { - doReceive(false); - } - - public void testAnonymousReceiveFails() throws JMSException { - doReceive(true); - } - - public void testAnonymousSendFails() throws JMSException { - doSend(true); - } - - public void testAnonymousSendSucceeds() throws JMSException { - doSend(false); - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestAnonymousReceiveSucceeds() { - addCombinationValues("userName", new Object[]{null}); - addCombinationValues("password", new Object[]{null}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("GUEST.BAR"), new ActiveMQTopic("GUEST.BAR")}); - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestAnonymousReceiveFails() { - addCombinationValues("userName", new Object[]{null}); - addCombinationValues("password", new Object[]{null}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("USERS.FOO"), new ActiveMQTopic("USERS.FOO")}); - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestAnonymousSendFails() { - addCombinationValues("userName", new Object[]{null}); - addCombinationValues("password", new Object[]{null}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("USERS.FOO"), new ActiveMQTopic("USERS.FOO")}); - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestAnonymousSendSucceeds() { - addCombinationValues("userName", new Object[]{null}); - addCombinationValues("password", new Object[]{null}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("GUEST.BAR"), new ActiveMQTopic("GUEST.BAR")}); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthenticationPluginSeparatorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthenticationPluginSeparatorTest.java deleted file mode 100644 index 82d27b423c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthenticationPluginSeparatorTest.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.activemq.security; - -import junit.framework.Test; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; - -public class SimpleAuthenticationPluginSeparatorTest extends SimpleAuthenticationPluginTest { - - public static Test suite() { - return suite(SimpleAuthenticationPluginSeparatorTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - @Override - protected BrokerService createBroker() throws Exception { - return createBroker("org/apache/activemq/security/simple-auth-separator.xml"); - } - - /** - * @see {@link CombinationTestSupport} - */ - @Override - public void initCombosForTestUserReceiveFails() { - addCombinationValues("userName", new Object[]{"user"}); - addCombinationValues("password", new Object[]{"password"}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("GUEST/BAR"), new ActiveMQTopic("GUEST/BAR")}); - } - - /** - * @see {@link CombinationTestSupport} - */ - @Override - public void initCombosForTestInvalidAuthentication() { - addCombinationValues("userName", new Object[]{"user"}); - addCombinationValues("password", new Object[]{"password"}); - } - - /** - * @see {@link CombinationTestSupport} - */ - @Override - public void initCombosForTestUserReceiveSucceeds() { - addCombinationValues("userName", new Object[]{"user"}); - addCombinationValues("password", new Object[]{"password"}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("USERS/FOO"), new ActiveMQTopic("USERS/FOO")}); - } - - /** - * @see {@link CombinationTestSupport} - */ - @Override - public void initCombosForTestGuestReceiveSucceeds() { - addCombinationValues("userName", new Object[]{"guest"}); - addCombinationValues("password", new Object[]{"password"}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("GUEST/BAR"), new ActiveMQTopic("GUEST/BAR")}); - } - - /** - * @see {@link org.apache.activemq.CombinationTestSupport} - */ - @Override - public void initCombosForTestGuestReceiveFails() { - addCombinationValues("userName", new Object[]{"guest"}); - addCombinationValues("password", new Object[]{"password"}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("USERS/FOO"), new ActiveMQTopic("USERS/FOO")}); - } - - /** - * @see {@link org.apache.activemq.CombinationTestSupport} - */ - @Override - public void initCombosForTestUserSendSucceeds() { - addCombinationValues("userName", new Object[]{"user"}); - addCombinationValues("password", new Object[]{"password"}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("USERS/FOO"), new ActiveMQQueue("GUEST/BAR"), new ActiveMQTopic("USERS/FOO"), new ActiveMQTopic("GUEST/BAR")}); - } - - /** - * @see {@link org.apache.activemq.CombinationTestSupport} - */ - @Override - public void initCombosForTestUserSendFails() { - addCombinationValues("userName", new Object[]{"user"}); - addCombinationValues("password", new Object[]{"password"}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST")}); - } - - /** - * @see {@link org.apache.activemq.CombinationTestSupport} - */ - @Override - public void initCombosForTestGuestSendFails() { - addCombinationValues("userName", new Object[]{"guest"}); - addCombinationValues("password", new Object[]{"password"}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("USERS/FOO"), new ActiveMQTopic("USERS/FOO")}); - } - - /** - * @see {@link org.apache.activemq.CombinationTestSupport} - */ - @Override - public void initCombosForTestGuestSendSucceeds() { - addCombinationValues("userName", new Object[]{"guest"}); - addCombinationValues("password", new Object[]{"password"}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("GUEST/BAR"), new ActiveMQTopic("GUEST/BAR")}); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthenticationPluginTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthenticationPluginTest.java deleted file mode 100644 index e8b68709d1..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthenticationPluginTest.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.activemq.security; - -import javax.jms.Connection; -import javax.jms.JMSException; -import javax.jms.JMSSecurityException; -import javax.jms.Message; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TemporaryTopic; -import javax.management.ObjectName; -import java.net.URI; - -import junit.framework.Test; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.CombinationTestSupport; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnection; -import org.apache.activemq.broker.TransportConnectionState; -import org.apache.activemq.broker.jmx.TopicViewMBean; -import org.apache.activemq.command.ActiveMQMessage; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.util.Wait; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SimpleAuthenticationPluginTest extends SecurityTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(SimpleAuthenticationPluginTest.class); - - public static Test suite() { - return suite(SimpleAuthenticationPluginTest.class); - } - - @Override - protected void setUp() throws Exception { - setAutoFail(true); - super.setUp(); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - @Override - protected BrokerService createBroker() throws Exception { - return createBroker("org/apache/activemq/security/simple-auth-broker.xml"); - } - - protected BrokerService createBroker(String uri) throws Exception { - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestPredefinedDestinations() { - addCombinationValues("userName", new Object[]{"guest"}); - addCombinationValues("password", new Object[]{"password"}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("TEST.Q")}); - } - - public void testPredefinedDestinations() throws JMSException { - Message sent = doSend(false); - assertEquals("guest", ((ActiveMQMessage) sent).getUserID()); - assertEquals("guest", sent.getStringProperty("JMSXUserID")); - } - - public void testTempDestinations() throws Exception { - Connection conn = factory.createConnection("guest", "password"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - String name = "org.apache.activemq:BrokerName=localhost,Type=TempTopic"; - try { - conn.start(); - TemporaryTopic temp = sess.createTemporaryTopic(); - name += ",Destination=" + temp.getTopicName().replaceAll(":", "_"); - fail("Should have failed creating a temp topic"); - } catch (Exception ignore) { - } - - ObjectName objName = new ObjectName(name); - TopicViewMBean mbean = (TopicViewMBean) broker.getManagementContext().newProxyInstance(objName, TopicViewMBean.class, true); - try { - System.out.println(mbean.getName()); - fail("Shouldn't have created a temp topic"); - } catch (Exception ignore) { - } - } - - public void testConnectionStartThrowsJMSSecurityException() throws Exception { - - Connection connection = factory.createConnection("badUser", "password"); - try { - connection.start(); - fail("Should throw JMSSecurityException"); - } catch (JMSSecurityException jmsEx) { - } catch (Exception e) { - LOG.info("Expected JMSSecurityException but was: {}", e.getClass()); - fail("Should throw JMSSecurityException"); - } - } - - public void testSecurityContextClearedOnPurge() throws Exception { - - connection.close(); - ActiveMQConnectionFactory tcpFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); - ActiveMQConnection conn = (ActiveMQConnection) tcpFactory.createConnection("user", "password"); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - - final int numDests = broker.getRegionBroker().getDestinations().length; - for (int i = 0; i < 10; i++) { - MessageProducer p = sess.createProducer(new ActiveMQQueue("USERS.PURGE." + i)); - p.close(); - } - - assertTrue("dests are purged", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("dests, orig: " + numDests + ", now: " + broker.getRegionBroker().getDestinations().length); - return (numDests + 1) == broker.getRegionBroker().getDestinations().length; - } - })); - - // verify removed from connection security context - TransportConnection brokerConnection = broker.getTransportConnectors().get(0).getConnections().get(0); - TransportConnectionState transportConnectionState = brokerConnection.lookupConnectionState(conn.getConnectionInfo().getConnectionId()); - assertEquals("no destinations", 0, transportConnectionState.getContext().getSecurityContext().getAuthorizedWriteDests().size()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthorizationMapTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthorizationMapTest.java deleted file mode 100644 index d45c79e2c6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleAuthorizationMapTest.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.activemq.security; - -/** - * - * - */ -public class SimpleAuthorizationMapTest extends AuthorizationMapTest { - - @Override - protected AuthorizationMap createAuthorizationMap() { - return SimpleSecurityBrokerSystemTest.createAuthorizationMap(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleSecurityBrokerSystemTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleSecurityBrokerSystemTest.java deleted file mode 100644 index 5139bf0fa9..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/SimpleSecurityBrokerSystemTest.java +++ /dev/null @@ -1,191 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.security; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.Session; -import javax.management.MBeanServer; -import javax.management.ObjectName; -import javax.management.openmbean.CompositeData; -import java.lang.management.ManagementFactory; -import java.net.URL; -import java.security.Principal; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import junit.framework.Test; - -import org.apache.activemq.CombinationTestSupport; -import org.apache.activemq.broker.Broker; -import org.apache.activemq.broker.BrokerPlugin; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.filter.DestinationMap; -import org.apache.activemq.jaas.GroupPrincipal; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Tests that the broker allows/fails access to destinations based on the - * security policy installed on the broker. - */ -public class SimpleSecurityBrokerSystemTest extends SecurityTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(SimpleSecurityBrokerSystemTest.class); - - public static final GroupPrincipal GUESTS = new GroupPrincipal("guests"); - public static final GroupPrincipal USERS = new GroupPrincipal("users"); - public static final GroupPrincipal ADMINS = new GroupPrincipal("admins"); - public static Principal WILDCARD; - - static { - try { - WILDCARD = (Principal) DefaultAuthorizationMap.createGroupPrincipal("*", GroupPrincipal.class.getName()); - } catch (Exception e) { - LOG.error("Failed to make wildcard principal", e); - } - } - - public BrokerPlugin authorizationPlugin; - public BrokerPlugin authenticationPlugin; - - static { - String path = System.getProperty("java.security.auth.login.config"); - if (path == null) { - URL resource = SimpleSecurityBrokerSystemTest.class.getClassLoader().getResource("login.config"); - if (resource != null) { - path = resource.getFile(); - System.setProperty("java.security.auth.login.config", path); - } - } - LOG.info("Path to login config: " + path); - } - - public static Test suite() { - return suite(SimpleSecurityBrokerSystemTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - /** - * @throws javax.jms.JMSException - */ - public void testPopulateJMSXUserID() throws Exception { - destination = new ActiveMQQueue("TEST"); - Connection connection = factory.createConnection("system", "manager"); - connections.add(connection); - connection.start(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - sendMessages(session, destination, 1); - - // make sure that the JMSXUserID is exposed over JMX - MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); - CompositeData[] browse = (CompositeData[]) mbs.invoke(new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=TEST"), "browse", null, null); - assertEquals("system", browse[0].get("JMSXUserID")); - - // And also via JMS. - MessageConsumer consumer = session.createConsumer(destination); - Message m = consumer.receive(1000); - assertTrue(m.propertyExists("JMSXUserID")); - assertEquals("system", m.getStringProperty("JMSXUserID")); - } - - public static AuthorizationMap createAuthorizationMap() { - DestinationMap readAccess = new DefaultAuthorizationMap(); - readAccess.put(new ActiveMQQueue(">"), ADMINS); - readAccess.put(new ActiveMQQueue("USERS.>"), USERS); - readAccess.put(new ActiveMQQueue("GUEST.>"), GUESTS); - readAccess.put(new ActiveMQTopic(">"), ADMINS); - readAccess.put(new ActiveMQTopic("USERS.>"), USERS); - readAccess.put(new ActiveMQTopic("GUEST.>"), GUESTS); - - DestinationMap writeAccess = new DefaultAuthorizationMap(); - writeAccess.put(new ActiveMQQueue(">"), ADMINS); - writeAccess.put(new ActiveMQQueue("USERS.>"), USERS); - writeAccess.put(new ActiveMQQueue("GUEST.>"), USERS); - writeAccess.put(new ActiveMQQueue("GUEST.>"), GUESTS); - writeAccess.put(new ActiveMQTopic(">"), ADMINS); - writeAccess.put(new ActiveMQTopic("USERS.>"), USERS); - writeAccess.put(new ActiveMQTopic("GUEST.>"), USERS); - writeAccess.put(new ActiveMQTopic("GUEST.>"), GUESTS); - - readAccess.put(new ActiveMQTopic("ActiveMQ.Advisory.>"), WILDCARD); - writeAccess.put(new ActiveMQTopic("ActiveMQ.Advisory.>"), WILDCARD); - - DestinationMap adminAccess = new DefaultAuthorizationMap(); - adminAccess.put(new ActiveMQTopic(">"), ADMINS); - adminAccess.put(new ActiveMQTopic(">"), USERS); - adminAccess.put(new ActiveMQTopic(">"), GUESTS); - adminAccess.put(new ActiveMQQueue(">"), ADMINS); - adminAccess.put(new ActiveMQQueue(">"), USERS); - adminAccess.put(new ActiveMQQueue(">"), GUESTS); - - return new SimpleAuthorizationMap(writeAccess, readAccess, adminAccess); - } - - public static class SimpleAuthenticationFactory implements BrokerPlugin { - - @Override - public Broker installPlugin(Broker broker) { - - HashMap u = new HashMap<>(); - u.put("system", "manager"); - u.put("user", "password"); - u.put("guest", "password"); - - Map> groups = new HashMap<>(); - groups.put("system", new HashSet<>(Arrays.asList(new Principal[]{ADMINS, USERS}))); - groups.put("user", new HashSet<>(Arrays.asList(new Principal[]{USERS}))); - groups.put("guest", new HashSet<>(Arrays.asList(new Principal[]{GUESTS}))); - - return new SimpleAuthenticationBroker(broker, u, groups); - } - - @Override - public String toString() { - return "SimpleAuthenticationBroker"; - } - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombos() { - addCombinationValues("authorizationPlugin", new Object[]{new AuthorizationPlugin(createAuthorizationMap())}); - addCombinationValues("authenticationPlugin", new Object[]{new SimpleAuthenticationFactory(), new JaasAuthenticationPlugin()}); - } - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - broker.setPopulateJMSXUserID(true); - broker.setUseAuthenticatedPrincipalForJMSXUserID(true); - broker.setPlugins(new BrokerPlugin[]{authorizationPlugin, authenticationPlugin}); - broker.setPersistent(false); - return broker; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubDoNothingCallbackHandler.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubDoNothingCallbackHandler.java deleted file mode 100644 index da9cb0ff34..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubDoNothingCallbackHandler.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.activemq.security; - -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.UnsupportedCallbackException; -import java.io.IOException; - -public class StubDoNothingCallbackHandler implements CallbackHandler { - - @Override - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubDualJaasConfiguration.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubDualJaasConfiguration.java deleted file mode 100644 index 34d2d9a84e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubDualJaasConfiguration.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.security; - -import javax.security.auth.login.AppConfigurationEntry; -import javax.security.auth.login.Configuration; - -public class StubDualJaasConfiguration extends Configuration { - - private AppConfigurationEntry nonSslConfigEntry; - private AppConfigurationEntry sslConfigEntry; - - public StubDualJaasConfiguration(AppConfigurationEntry nonSslConfigEntry, AppConfigurationEntry sslConfigEntry) { - this.nonSslConfigEntry = nonSslConfigEntry; - this.sslConfigEntry = sslConfigEntry; - } - - @Override - public AppConfigurationEntry[] getAppConfigurationEntry(String name) { - if ("activemq-domain".equals(name)) { - return new AppConfigurationEntry[]{nonSslConfigEntry}; - } else { - return new AppConfigurationEntry[]{sslConfigEntry}; - } - } - - @Override - public void refresh() { - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubJaasConfiguration.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubJaasConfiguration.java deleted file mode 100644 index 0023d5b0a1..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubJaasConfiguration.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.activemq.security; - -import javax.security.auth.login.AppConfigurationEntry; -import javax.security.auth.login.Configuration; - -public class StubJaasConfiguration extends Configuration { - - private AppConfigurationEntry configEntry; - - public StubJaasConfiguration(AppConfigurationEntry configEntry) { - this.configEntry = configEntry; - } - - @Override - public AppConfigurationEntry[] getAppConfigurationEntry(String name) { - return new AppConfigurationEntry[]{configEntry}; - } - - @Override - public void refresh() { - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubLoginModule.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubLoginModule.java deleted file mode 100644 index 72bdd0b1f6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubLoginModule.java +++ /dev/null @@ -1,98 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.security; - -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.login.FailedLoginException; -import javax.security.auth.login.LoginException; -import javax.security.auth.spi.LoginModule; -import java.util.Map; - -import org.apache.activemq.jaas.GroupPrincipal; -import org.apache.activemq.jaas.UserPrincipal; - -public class StubLoginModule implements LoginModule { - - public static final String ALLOW_LOGIN_PROPERTY = "org.apache.activemq.jaas.stubproperties.allow_login"; - public static final String USERS_PROPERTY = "org.apache.activemq.jaas.stubproperties.users"; - public static final String GROUPS_PROPERTY = "org.apache.activemq.jaas.stubproperties.groups"; - - private Subject subject; - - private String userNames[]; - private String groupNames[]; - private boolean allowLogin; - - @Override - @SuppressWarnings("rawtypes") - public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) { - String allowLoginString = (String) (options.get(ALLOW_LOGIN_PROPERTY)); - String usersString = (String) (options.get(USERS_PROPERTY)); - String groupsString = (String) (options.get(GROUPS_PROPERTY)); - - this.subject = subject; - - allowLogin = Boolean.parseBoolean(allowLoginString); - userNames = usersString.split(","); - groupNames = groupsString.split(","); - } - - @Override - public boolean login() throws LoginException { - if (!allowLogin) { - throw new FailedLoginException("Login was not allowed (as specified in configuration)."); - } - - return true; - } - - @Override - public boolean commit() throws LoginException { - if (!allowLogin) { - throw new FailedLoginException("Login was not allowed (as specified in configuration)."); - } - - for (int i = 0; i < userNames.length; ++i) { - if (userNames[i].length() > 0) { - subject.getPrincipals().add(new UserPrincipal(userNames[i])); - } - } - - for (int i = 0; i < groupNames.length; ++i) { - if (groupNames[i].length() > 0) { - subject.getPrincipals().add(new GroupPrincipal(groupNames[i])); - } - } - - return true; - } - - @Override - public boolean abort() throws LoginException { - return true; - } - - @Override - public boolean logout() throws LoginException { - subject.getPrincipals().clear(); - - return true; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubSecurityContext.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubSecurityContext.java deleted file mode 100644 index 11317b787b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/StubSecurityContext.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.activemq.security; - -import java.security.Principal; -import java.util.Set; - -public class StubSecurityContext extends SecurityContext { - - StubSecurityContext() { - super(""); - } - - @Override - public Set getPrincipals() { - return null; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityTest.java deleted file mode 100644 index 90dcf397b2..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.security; - -import java.net.URI; - -import junit.framework.Test; - -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * - */ -public class XBeanSecurityTest extends SecurityTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(XBeanSecurityTest.class); - - public static Test suite() { - return suite(XBeanSecurityTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - @Override - protected BrokerService createBroker() throws Exception { - return createBroker("org/apache/activemq/security/jaas-broker.xml"); - } - - protected BrokerService createBroker(String uri) throws Exception { - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityWithGuestNoCredentialsOnlyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityWithGuestNoCredentialsOnlyTest.java deleted file mode 100644 index 00537c3584..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityWithGuestNoCredentialsOnlyTest.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.activemq.security; - -import javax.jms.Connection; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.net.URI; - -import junit.framework.Test; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.CombinationTestSupport; -import org.apache.activemq.JmsTestSupport; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQMessage; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class XBeanSecurityWithGuestNoCredentialsOnlyTest extends JmsTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(XBeanSecurityWithGuestNoCredentialsOnlyTest.class); - public ActiveMQDestination destination; - - public static Test suite() { - return suite(XBeanSecurityWithGuestNoCredentialsOnlyTest.class); - } - - public void testUserSendGoodPassword() throws JMSException { - Message m = doSend(false); - assertEquals("system", ((ActiveMQMessage) m).getUserID()); - assertEquals("system", m.getStringProperty("JMSXUserID")); - } - - public void testUserSendWrongPassword() throws JMSException { - try { - doSend(true); - fail("expect exception on connect"); - } catch (JMSException expected) { - assertTrue("cause as expected", expected.getCause() instanceof SecurityException); - } - } - - public void testUserSendNoCredentials() throws JMSException { - Message m = doSend(false); - // note brokerService.useAuthenticatedPrincipalForJMXUserID=true for this - assertEquals("guest", ((ActiveMQMessage) m).getUserID()); - assertEquals("guest", m.getStringProperty("JMSXUserID")); - } - - @Override - protected BrokerService createBroker() throws Exception { - return createBroker("org/apache/activemq/security/jaas-broker-guest-no-creds-only.xml"); - } - - protected BrokerService createBroker(String uri) throws Exception { - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } - - public Message doSend(boolean fail) throws JMSException { - - Connection adminConnection = factory.createConnection("system", "manager"); - connections.add(adminConnection); - - adminConnection.start(); - Session adminSession = adminConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = adminSession.createConsumer(destination); - - connections.remove(connection); - connection = (ActiveMQConnection) factory.createConnection(userName, password); - connections.add(connection); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - try { - sendMessages(session, destination, 1); - } catch (JMSException e) { - // If test is expected to fail, the cause must only be a - // SecurityException - // otherwise rethrow the exception - if (!fail || !(e.getCause() instanceof SecurityException)) { - throw e; - } - } - - Message m = consumer.receive(1000); - if (fail) { - assertNull(m); - } else { - assertNotNull(m); - assertEquals("0", ((TextMessage) m).getText()); - assertNull(consumer.receiveNoWait()); - } - return m; - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestUserSendGoodPassword() { - addCombinationValues("userName", new Object[]{"system"}); - addCombinationValues("password", new Object[]{"manager"}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("test"), new ActiveMQTopic("test")}); - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestUserSendWrongPassword() { - addCombinationValues("userName", new Object[]{"system"}); - addCombinationValues("password", new Object[]{"wrongpassword"}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("GuestQueue")}); - } - - public void initCombosForTestUserSendNoCredentials() { - addCombinationValues("userName", new Object[]{null, "system"}); - addCombinationValues("password", new Object[]{null}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("GuestQueue")}); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityWithGuestTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityWithGuestTest.java deleted file mode 100644 index 4b7db21b0c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSecurityWithGuestTest.java +++ /dev/null @@ -1,140 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.security; - -import javax.jms.Connection; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.net.URI; - -import junit.framework.Test; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.CombinationTestSupport; -import org.apache.activemq.JmsTestSupport; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQMessage; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class XBeanSecurityWithGuestTest extends JmsTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(XBeanSecurityWithGuestTest.class); - public ActiveMQDestination destination; - - public static Test suite() { - return suite(XBeanSecurityWithGuestTest.class); - } - - public void testUserSendGoodPassword() throws JMSException { - Message m = doSend(false); - assertEquals("system", ((ActiveMQMessage) m).getUserID()); - assertEquals("system", m.getStringProperty("JMSXUserID")); - } - - public void testUserSendWrongPassword() throws JMSException { - Message m = doSend(false); - // note brokerService.useAuthenticatedPrincipalForJMXUserID=true for this - assertEquals("guest", ((ActiveMQMessage) m).getUserID()); - assertEquals("guest", m.getStringProperty("JMSXUserID")); - } - - public void testUserSendNoCredentials() throws JMSException { - Message m = doSend(false); - // note brokerService.useAuthenticatedPrincipalForJMXUserID=true for this - assertEquals("guest", ((ActiveMQMessage) m).getUserID()); - assertEquals("guest", m.getStringProperty("JMSXUserID")); - } - - @Override - protected BrokerService createBroker() throws Exception { - return createBroker("org/apache/activemq/security/jaas-broker-guest.xml"); - } - - protected BrokerService createBroker(String uri) throws Exception { - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } - - public Message doSend(boolean fail) throws JMSException { - - Connection adminConnection = factory.createConnection("system", "manager"); - connections.add(adminConnection); - - adminConnection.start(); - Session adminSession = adminConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = adminSession.createConsumer(destination); - - connections.remove(connection); - connection = (ActiveMQConnection) factory.createConnection(userName, password); - connections.add(connection); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - try { - sendMessages(session, destination, 1); - } catch (JMSException e) { - // If test is expected to fail, the cause must only be a - // SecurityException - // otherwise rethrow the exception - if (!fail || !(e.getCause() instanceof SecurityException)) { - throw e; - } - } - - Message m = consumer.receive(1000); - if (fail) { - assertNull(m); - } else { - assertNotNull(m); - assertEquals("0", ((TextMessage) m).getText()); - assertNull(consumer.receiveNoWait()); - } - return m; - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestUserSendGoodPassword() { - addCombinationValues("userName", new Object[]{"system"}); - addCombinationValues("password", new Object[]{"manager"}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("test"), new ActiveMQTopic("test")}); - } - - /** - * @see {@link CombinationTestSupport} - */ - public void initCombosForTestUserSendWrongPassword() { - addCombinationValues("userName", new Object[]{"system"}); - addCombinationValues("password", new Object[]{"wrongpassword"}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("GuestQueue")}); - } - - public void initCombosForTestUserSendNoCredentials() { - addCombinationValues("userName", new Object[]{"", null}); - addCombinationValues("password", new Object[]{"", null}); - addCombinationValues("destination", new Object[]{new ActiveMQQueue("GuestQueue")}); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSslContextTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSslContextTest.java deleted file mode 100644 index 2e7c2da3e1..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/XBeanSslContextTest.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.activemq.security; - -import java.net.URI; - -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.junit.After; -import org.junit.Test; - -public class XBeanSslContextTest { - - BrokerService broker; - - @Test - public void testSslContextElement() throws Exception { - broker = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/security/activemq-sslcontext.xml")); - } - - @After - public void stopBroker() throws Exception { - if (broker != null) - broker.stop(); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-add.ldif b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-add.ldif deleted file mode 100644 index e9235f3848..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-add.ldif +++ /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. -## --------------------------------------------------------------------------- - - -## FAILED - -dn: cn=FAILED,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: FAILED -description: New queue -objectClass: applicationProcess -objectClass: top - -dn: cn=admin,cn=FAILED,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: admin -description: Admin privilege group, members are roles -member: cn=users,ou=Group,ou=ActiveMQ,ou=system -member: cn=admins,ou=Group,ou=ActiveMQ,ou=system -objectClass: groupOfNames -objectClass: top - -dn: cn=read,cn=FAILED,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: read -member: cn=users,ou=Group,ou=ActiveMQ,ou=system -member: cn=admins,ou=Group,ou=ActiveMQ,ou=system -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=FAILED,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: write -objectClass: groupOfNames -objectClass: top -member: cn=users,ou=Group,ou=ActiveMQ,ou=system -member: cn=admins,ou=Group,ou=ActiveMQ,ou=system diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-delete.ldif b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-delete.ldif deleted file mode 100644 index 45e4f887e9..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-delete.ldif +++ /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. -## --------------------------------------------------------------------------- - -dn: cn=admin,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -changetype: delete - - -dn: cn=read,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -changetype: delete - -dn: cn=write,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -changetype: delete - -dn: cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -changetype: delete - -dn: cn=read,ou=Temp,ou=Destination,ou=ActiveMQ,ou=system -changetype: delete - -dn: cn=write,ou=Temp,ou=Destination,ou=ActiveMQ,ou=system -changetype: delete - -dn: cn=admin,ou=Temp,ou=Destination,ou=ActiveMQ,ou=system -changetype: delete - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-legacy-add.ldif b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-legacy-add.ldif deleted file mode 100644 index 48f8b6a7f6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-legacy-add.ldif +++ /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. -## --------------------------------------------------------------------------- - - -## FAILED - -dn: cn=FAILED,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: FAILED -description: New queue -objectClass: applicationProcess -objectClass: top - -dn: cn=admin,cn=FAILED,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: admin -description: Admin privilege group, members are roles -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=read,cn=FAILED,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: read -member: cn=users -member: cn=admins -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=FAILED,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: write -objectClass: groupOfNames -objectClass: top -member: cn=users -member: cn=admins diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-legacy-delete.ldif b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-legacy-delete.ldif deleted file mode 100644 index 9cc98920a8..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-legacy-delete.ldif +++ /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. -## --------------------------------------------------------------------------- - -dn: cn=admin,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -changetype: delete - -dn: cn=read,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -changetype: delete - -dn: cn=write,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -changetype: delete - -dn: cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -changetype: delete - -dn: cn=read,ou=Temp,ou=Destination,ou=ActiveMQ,ou=system -changetype: delete - -dn: cn=write,ou=Temp,ou=Destination,ou=ActiveMQ,ou=system -changetype: delete - -dn: cn=admin,ou=Temp,ou=Destination,ou=ActiveMQ,ou=system -changetype: delete - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-legacy.ldif b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-legacy.ldif deleted file mode 100644 index 3ad7459afe..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-legacy.ldif +++ /dev/null @@ -1,264 +0,0 @@ -## --------------------------------------------------------------------------- -## Licensed to the Apache Software Foundation (ASF) under one or more -## contributor license agreements. See the NOTICE file distributed with -## this work for additional information regarding copyright ownership. -## The ASF licenses this file to You under the Apache License, Version 2.0 -## (the "License"); you may not use this file except in compliance with -## the License. You may obtain a copy of the License at -## -## http://www.apache.org/licenses/LICENSE-2.0 -## -## Unless required by applicable law or agreed to in writing, software -## distributed under the License is distributed on an "AS IS" BASIS, -## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -## See the License for the specific language governing permissions and -## limitations under the License. -## --------------------------------------------------------------------------- - - -########################## -## Define basic objects ## -########################## - -dn: ou=ActiveMQ,ou=system -objectClass: organizationalUnit -objectClass: top -ou: ActiveMQ - -dn: ou=Services,ou=system -ou: Services -objectClass: organizationalUnit -objectClass: top - -dn: cn=mqbroker,ou=Services,ou=system -cn: mqbroker -objectClass: organizationalRole -objectClass: top -objectClass: simpleSecurityObject -userPassword: {SSHA}YvMAkkd66cDecNoejo8jnw5uUUBziyl0 -description: Bind user for MQ broker - - -################### -## Define groups ## -################### - - -dn: ou=Group,ou=ActiveMQ,ou=system -objectClass: organizationalUnit -objectClass: top -ou: Group - -dn: cn=admins,ou=Group,ou=ActiveMQ,ou=system -cn: admins -member: uid=admin -objectClass: groupOfNames -objectClass: top - -dn: cn=users,ou=Group,ou=ActiveMQ,ou=system -cn: users -member: uid=jdoe -objectClass: groupOfNames -objectClass: top - - -################## -## Define users ## -################## - - -dn: ou=User,ou=ActiveMQ,ou=system -objectClass: organizationalUnit -objectClass: top -ou: User - -dn: uid=admin,ou=User,ou=ActiveMQ,ou=system -uid: admin -userPassword: {SSHA}YvMAkkd66cDecNoejo8jnw5uUUBziyl0 -objectClass: account -objectClass: simpleSecurityObject -objectClass: top - - -dn: uid=jdoe,ou=User,ou=ActiveMQ,ou=system -uid: jdoe -userPassword: {SSHA}YvMAkkd66cDecNoejo8jnw5uUUBziyl0 -objectclass: inetOrgPerson -objectclass: organizationalPerson -objectclass: person -objectclass: top -cn: Jane Doe -sn: Doe - - -######################### -## Define destinations ## -######################### - -dn: ou=Destination,ou=ActiveMQ,ou=system -objectClass: organizationalUnit -objectClass: top -ou: Destination - -dn: ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -objectClass: organizationalUnit -objectClass: top -ou: Topic - -dn: ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -objectClass: organizationalUnit -objectClass: top -ou: Queue - -## TEST.FOO - -dn: cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: TEST.FOO -description: A queue -objectClass: applicationProcess -objectClass: top - -dn: cn=admin,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: admin -description: Admin privilege group, members are roles -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=read,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: read -member: cn=users -member: cn=admins -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: write -objectClass: groupOfNames -objectClass: top -member: cn=users -member: cn=admins - - -## FOO.> - -dn: cn=FOO.$,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: FOO.$ -description: A queue -objectClass: applicationProcess -objectClass: top - -dn: cn=admin,cn=FOO.$,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: admin -description: Admin privilege group, members are roles -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=read,cn=FOO.$,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: read -member: cn=users -member: cn=admins -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=FOO.$,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: write -objectClass: groupOfNames -objectClass: top -member: cn=users -member: cn=admins - - -## BAR.* - -dn: cn=BAR.*,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: BAR.* -description: A queue -objectClass: applicationProcess -objectClass: top - -dn: cn=admin,cn=BAR.*,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: admin -description: Admin privilege group, members are roles -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=read,cn=BAR.*,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: read -member: cn=users -member: cn=admins -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=BAR.*,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: write -objectClass: groupOfNames -objectClass: top -member: cn=users -member: cn=admins - -####################### -## Define advisories ## -####################### - -dn: cn=ActiveMQ.Advisory.$,ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -cn: ActiveMQ.Advisory.$ -objectClass: applicationProcess -objectClass: top -description: Advisory topics - -dn: cn=read,cn=ActiveMQ.Advisory.$,ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -cn: read -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=ActiveMQ.Advisory.$,ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -cn: write -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=admin,cn=ActiveMQ.Advisory.$,ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -cn: admin -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -###################### -## Define temporary ## -###################### - -dn: ou=Temp,ou=Destination,ou=ActiveMQ,ou=system -objectClass: organizationalUnit -objectClass: top -ou: Temp - -dn: cn=read,ou=Temp,ou=Destination,ou=ActiveMQ,ou=system -cn: read -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=write,ou=Temp,ou=Destination,ou=ActiveMQ,ou=system -cn: write -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=admin,ou=Temp,ou=Destination,ou=ActiveMQ,ou=system -cn: admin -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-legacy.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-legacy.xml deleted file mode 100644 index 911acba553..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds-legacy.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds.ldif b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds.ldif deleted file mode 100644 index afe6816c88..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds.ldif +++ /dev/null @@ -1,294 +0,0 @@ -## --------------------------------------------------------------------------- -## Licensed to the Apache Software Foundation (ASF) under one or more -## contributor license agreements. See the NOTICE file distributed with -## this work for additional information regarding copyright ownership. -## The ASF licenses this file to You under the Apache License, Version 2.0 -## (the "License"); you may not use this file except in compliance with -## the License. You may obtain a copy of the License at -## -## http://www.apache.org/licenses/LICENSE-2.0 -## -## Unless required by applicable law or agreed to in writing, software -## distributed under the License is distributed on an "AS IS" BASIS, -## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -## See the License for the specific language governing permissions and -## limitations under the License. -## --------------------------------------------------------------------------- - - -########################## -## Define basic objects ## -########################## - -dn: ou=ActiveMQ,ou=system -objectClass: organizationalUnit -objectClass: top -ou: ActiveMQ - -dn: ou=Services,ou=system -ou: Services -objectClass: organizationalUnit -objectClass: top - -dn: cn=mqbroker,ou=Services,ou=system -cn: mqbroker -objectClass: organizationalRole -objectClass: top -objectClass: simpleSecurityObject -userPassword: {SSHA}YvMAkkd66cDecNoejo8jnw5uUUBziyl0 -description: Bind user for MQ broker - - -################### -## Define groups ## -################### - - -dn: ou=Group,ou=ActiveMQ,ou=system -objectClass: organizationalUnit -objectClass: top -ou: Group - -dn: cn=admins,ou=Group,ou=ActiveMQ,ou=system -cn: admins -member: uid=admin,ou=User,ou=ActiveMQ,ou=system -objectClass: groupOfNames -objectClass: top - -dn: cn=users,ou=Group,ou=ActiveMQ,ou=system -cn: users -member: uid=jdoe,ou=User,ou=ActiveMQ,ou=system -objectClass: groupOfNames -objectClass: top - - -################## -## Define users ## -################## - - -dn: ou=User,ou=ActiveMQ,ou=system -objectClass: organizationalUnit -objectClass: top -ou: User - -dn: uid=admin,ou=User,ou=ActiveMQ,ou=system -uid: admin -userPassword: {SSHA}YvMAkkd66cDecNoejo8jnw5uUUBziyl0 -objectClass: account -objectClass: simpleSecurityObject -objectClass: top - - -dn: uid=jdoe,ou=User,ou=ActiveMQ,ou=system -uid: jdoe -userPassword: {SSHA}YvMAkkd66cDecNoejo8jnw5uUUBziyl0 -objectclass: inetOrgPerson -objectclass: organizationalPerson -objectclass: person -objectclass: top -cn: Jane Doe -sn: Doe - - -######################### -## Define destinations ## -######################### - -dn: ou=Destination,ou=ActiveMQ,ou=system -objectClass: organizationalUnit -objectClass: top -ou: Destination - -dn: ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -objectClass: organizationalUnit -objectClass: top -ou: Topic - -dn: ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -objectClass: organizationalUnit -objectClass: top -ou: Queue - -## TEST.FOO - -dn: cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: TEST.FOO -description: A queue -objectClass: applicationProcess -objectClass: top - -dn: cn=admin,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: admin -description: Admin privilege group, members are roles -member: cn=users,ou=Group,ou=ActiveMQ,ou=system -member: cn=admins,ou=Group,ou=ActiveMQ,ou=system -objectClass: groupOfNames -objectClass: top - -dn: cn=read,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: read -member: cn=users,ou=Group,ou=ActiveMQ,ou=system -member: cn=admins,ou=Group,ou=ActiveMQ,ou=system -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: write -objectClass: groupOfNames -objectClass: top -member: cn=users,ou=Group,ou=ActiveMQ,ou=system -member: cn=admins,ou=Group,ou=ActiveMQ,ou=system - -## TEST.FOOBAR - -dn: cn=TEST.FOOBAR,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: TEST.BAR -description: A queue -objectClass: applicationProcess -objectClass: top - -dn: cn=admin,cn=TEST.FOOBAR,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: admin -description: Admin privilege group, members are roles -member: cn=admins,ou=Group,ou=ActiveMQ,ou=system -member: cn=users,ou=Group,ou=ActiveMQ,ou=system -objectClass: groupOfNames -objectClass: top - -dn: cn=read,cn=TEST.FOOBAR,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: read -member: cn=users,ou=Group,ou=ActiveMQ,ou=system -member: cn=admins,ou=Group,ou=ActiveMQ,ou=system -member: uid=jdoe,ou=User,ou=ActiveMQ,ou=system -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=TEST.FOOBAR,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: write -objectClass: groupOfNames -objectClass: top -member: cn=users,ou=Group,ou=ActiveMQ,ou=system -member: cn=admins,ou=Group,ou=ActiveMQ,ou=system -member: uid=jdoe,ou=User,ou=ActiveMQ,ou=system - -## FOO.> - -dn: cn=FOO.$,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: FOO.$ -description: A queue -objectClass: applicationProcess -objectClass: top - -dn: cn=admin,cn=FOO.$,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: admin -description: Admin privilege group, members are roles -member: cn=admins,ou=Group,ou=ActiveMQ,ou=system -member: cn=users,ou=Group,ou=ActiveMQ,ou=system -objectClass: groupOfNames -objectClass: top - -dn: cn=read,cn=FOO.$,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: read -member: cn=users,ou=Group,ou=ActiveMQ,ou=system -member: cn=admins,ou=Group,ou=ActiveMQ,ou=system -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=FOO.$,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: write -objectClass: groupOfNames -objectClass: top -member: cn=users,ou=Group,ou=ActiveMQ,ou=system -member: cn=admins,ou=Group,ou=ActiveMQ,ou=system - -## BAR.* - -dn: cn=BAR.*,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: BAR.* -description: A queue -objectClass: applicationProcess -objectClass: top - -dn: cn=admin,cn=BAR.*,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: admin -description: Admin privilege group, members are roles -member: cn=admins,ou=Group,ou=ActiveMQ,ou=system -member: cn=users,ou=Group,ou=ActiveMQ,ou=system -objectClass: groupOfNames -objectClass: top - -dn: cn=read,cn=BAR.*,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: read -member: cn=users,ou=Group,ou=ActiveMQ,ou=system -member: cn=admins,ou=Group,ou=ActiveMQ,ou=system -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=BAR.*,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: write -objectClass: groupOfNames -objectClass: top -member: cn=users,ou=Group,ou=ActiveMQ,ou=system -member: cn=admins,ou=Group,ou=ActiveMQ,ou=system - -####################### -## Define advisories ## -####################### - -dn: cn=ActiveMQ.Advisory.$,ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -cn: ActiveMQ.Advisory.$ -objectClass: applicationProcess -objectClass: top -description: Advisory topics - -dn: cn=read,cn=ActiveMQ.Advisory.$,ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -cn: read -member: cn=admins,ou=Group,ou=ActiveMQ,ou=system -member: cn=users,ou=Group,ou=ActiveMQ,ou=system -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=ActiveMQ.Advisory.$,ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -cn: write -member: cn=admins,ou=Group,ou=ActiveMQ,ou=system -member: cn=users,ou=Group,ou=ActiveMQ,ou=system -objectClass: groupOfNames -objectClass: top - -dn: cn=admin,cn=ActiveMQ.Advisory.$,ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -cn: admin -member: cn=admins,ou=Group,ou=ActiveMQ,ou=system -member: cn=users,ou=Group,ou=ActiveMQ,ou=system -objectClass: groupOfNames -objectClass: top - -###################### -## Define temporary ## -###################### - -dn: ou=Temp,ou=Destination,ou=ActiveMQ,ou=system -objectClass: organizationalUnit -objectClass: top -ou: Temp - -dn: cn=read,ou=Temp,ou=Destination,ou=ActiveMQ,ou=system -cn: read -member: cn=admins,ou=Group,ou=ActiveMQ,ou=system -member: cn=users,ou=Group,ou=ActiveMQ,ou=system -objectClass: groupOfNames -objectClass: top - -dn: cn=write,ou=Temp,ou=Destination,ou=ActiveMQ,ou=system -cn: write -member: cn=admins,ou=Group,ou=ActiveMQ,ou=system -member: cn=users,ou=Group,ou=ActiveMQ,ou=system -objectClass: groupOfNames -objectClass: top - -dn: cn=admin,ou=Temp,ou=Destination,ou=ActiveMQ,ou=system -cn: admin -member: cn=admins,ou=Group,ou=ActiveMQ,ou=system -member: cn=users,ou=Group,ou=ActiveMQ,ou=system -objectClass: groupOfNames -objectClass: top diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds.xml deleted file mode 100644 index 67768c1491..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-apacheds.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-ldap-auth.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-ldap-auth.xml deleted file mode 100644 index 8a11a6a483..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-ldap-auth.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-ldap.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-ldap.xml deleted file mode 100644 index 3ab048cabf..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-ldap.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap-add.ldif b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap-add.ldif deleted file mode 100644 index 34beb9f348..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap-add.ldif +++ /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. -## --------------------------------------------------------------------------- - - -## FAILED - -dn: cn=FAILED,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: FAILED -description: New queue -objectClass: applicationProcess -objectClass: top - -dn: cn=admin,cn=FAILED,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: admin -description: Admin privilege group, members are roles -member: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: groupOfNames -objectClass: top - -dn: cn=read,cn=FAILED,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: read -member: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=FAILED,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: write -objectClass: groupOfNames -objectClass: top -member: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap-delete.ldif b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap-delete.ldif deleted file mode 100644 index f7767811dc..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap-delete.ldif +++ /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. -## --------------------------------------------------------------------------- - -dn: cn=admin,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -changetype: delete - -dn: cn=read,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -changetype: delete - -dn: cn=write,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -changetype: delete - -dn: cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -changetype: delete - -dn: cn=read,ou=Temp,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -changetype: delete - -dn: cn=write,ou=Temp,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -changetype: delete - -dn: cn=admin,ou=Temp,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -changetype: delete - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap-legacy-add.ldif b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap-legacy-add.ldif deleted file mode 100644 index 1c146de509..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap-legacy-add.ldif +++ /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. -## --------------------------------------------------------------------------- - - -## FAILED - -dn: cn=FAILED,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: FAILED -description: New queue -objectClass: applicationProcess -objectClass: top - -dn: cn=admin,cn=FAILED,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: admin -description: Admin privilege group, members are roles -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=read,cn=FAILED,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: read -member: cn=users -member: cn=admins -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=FAILED,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: write -objectClass: groupOfNames -objectClass: top -member: cn=users -member: cn=admins diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap-legacy-delete.ldif b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap-legacy-delete.ldif deleted file mode 100644 index f7767811dc..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap-legacy-delete.ldif +++ /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. -## --------------------------------------------------------------------------- - -dn: cn=admin,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -changetype: delete - -dn: cn=read,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -changetype: delete - -dn: cn=write,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -changetype: delete - -dn: cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -changetype: delete - -dn: cn=read,ou=Temp,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -changetype: delete - -dn: cn=write,ou=Temp,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -changetype: delete - -dn: cn=admin,ou=Temp,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -changetype: delete - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap-legacy.ldif b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap-legacy.ldif deleted file mode 100644 index f9d2a2f47b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap-legacy.ldif +++ /dev/null @@ -1,281 +0,0 @@ -## --------------------------------------------------------------------------- -## Licensed to the Apache Software Foundation (ASF) under one or more -## contributor license agreements. See the NOTICE file distributed with -## this work for additional information regarding copyright ownership. -## The ASF licenses this file to You under the Apache License, Version 2.0 -## (the "License"); you may not use this file except in compliance with -## the License. You may obtain a copy of the License at -## -## http://www.apache.org/licenses/LICENSE-2.0 -## -## Unless required by applicable law or agreed to in writing, software -## distributed under the License is distributed on an "AS IS" BASIS, -## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -## See the License for the specific language governing permissions and -## limitations under the License. -## --------------------------------------------------------------------------- - - -########################## -## Define basic objects ## -########################## - -dn: dc=apache,dc=org -objectClass: dcObject -objectClass: organization -dc: apache -o: Apache - -dn: dc=activemq,dc=apache,dc=org -objectClass: dcObject -objectClass: container -objectClass: top -cn: activemq -dc: activemq - -dn: ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: organizationalUnit -objectClass: top -ou: ActiveMQ - -dn: ou=Services,dc=activemq,dc=apache,dc=org -ou: Services -objectClass: organizationalUnit -objectClass: top - -dn: cn=mqbroker,ou=Services,dc=activemq,dc=apache,dc=org -cn: mqbroker -objectClass: organizationalRole -objectClass: top -objectClass: simpleSecurityObject -userPassword: {SSHA}YvMAkkd66cDecNoejo8jnw5uUUBziyl0 -description: Bind user for MQ broker - - -################### -## Define groups ## -################### - - -dn: ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: organizationalUnit -objectClass: top -ou: Group - -dn: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: admins -member: uid=admin -objectClass: groupOfNames -objectClass: top - -dn: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: users -member: uid=jdoe -objectClass: groupOfNames -objectClass: top - - -################## -## Define users ## -################## - - -dn: ou=User,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: organizationalUnit -objectClass: top -ou: User - -dn: uid=admin,ou=User,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -uid: admin -userPassword: {SSHA}YvMAkkd66cDecNoejo8jnw5uUUBziyl0 -objectclass: uidObject -objectclass: organizationalPerson -objectclass: person -objectclass: top -cn: Admin -sn: Admin - - -dn: uid=jdoe,ou=User,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -uid: jdoe -userPassword: {SSHA}YvMAkkd66cDecNoejo8jnw5uUUBziyl0 -objectclass: uidObject -objectclass: organizationalPerson -objectclass: person -objectclass: top -cn: Jane Doe -sn: Doe - - -######################### -## Define destinations ## -######################### - -dn: ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: organizationalUnit -objectClass: top -ou: Destination - -dn: ou=Topic,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: organizationalUnit -objectClass: top -ou: Topic - -dn: ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: organizationalUnit -objectClass: top -ou: Queue - -## TEST.FOO - -dn: cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: TEST.FOO -description: A queue -objectClass: applicationProcess -objectClass: top - -dn: cn=admin,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: admin -description: Admin privilege group, members are roles -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=read,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: read -member: cn=users -member: cn=admins -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: write -objectClass: groupOfNames -objectClass: top -member: cn=users -member: cn=admins - - -## FOO.> - -dn: cn=FOO.$,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: FOO.$ -description: A queue -objectClass: applicationProcess -objectClass: top - -dn: cn=admin,cn=FOO.$,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: admin -description: Admin privilege group, members are roles -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=read,cn=FOO.$,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: read -member: cn=users -member: cn=admins -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=FOO.$,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: write -objectClass: groupOfNames -objectClass: top -member: cn=users -member: cn=admins - - -## BAR.* - -dn: cn=BAR.*,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: BAR.* -description: A queue -objectClass: applicationProcess -objectClass: top - -dn: cn=admin,cn=BAR.*,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: admin -description: Admin privilege group, members are roles -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=read,cn=BAR.*,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: read -member: cn=users -member: cn=admins -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=BAR.*,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: write -objectClass: groupOfNames -objectClass: top -member: cn=users -member: cn=admins - -####################### -## Define advisories ## -####################### - -dn: cn=ActiveMQ.Advisory.$,ou=Topic,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: ActiveMQ.Advisory.$ -objectClass: applicationProcess -objectClass: top -description: Advisory topics - -dn: cn=read,cn=ActiveMQ.Advisory.$,ou=Topic,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: read -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=ActiveMQ.Advisory.$,ou=Topic,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: write -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=admin,cn=ActiveMQ.Advisory.$,ou=Topic,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: admin -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -###################### -## Define temporary ## -###################### - -dn: ou=Temp,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: organizationalUnit -objectClass: top -ou: Temp - -dn: cn=read,ou=Temp,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: read -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=write,ou=Temp,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: write -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=admin,ou=Temp,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: admin -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap.ldif b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap.ldif deleted file mode 100644 index 222c6fac39..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap.ldif +++ /dev/null @@ -1,312 +0,0 @@ -## --------------------------------------------------------------------------- -## Licensed to the Apache Software Foundation (ASF) under one or more -## contributor license agreements. See the NOTICE file distributed with -## this work for additional information regarding copyright ownership. -## The ASF licenses this file to You under the Apache License, Version 2.0 -## (the "License"); you may not use this file except in compliance with -## the License. You may obtain a copy of the License at -## -## http://www.apache.org/licenses/LICENSE-2.0 -## -## Unless required by applicable law or agreed to in writing, software -## distributed under the License is distributed on an "AS IS" BASIS, -## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -## See the License for the specific language governing permissions and -## limitations under the License. -## --------------------------------------------------------------------------- - - -########################## -## Define basic objects ## -########################## - -dn: dc=apache,dc=org -objectClass: dcObject -objectClass: organization -dc: apache -o: Apache - -dn: dc=activemq,dc=apache,dc=org -objectClass: dcObject -objectClass: container -objectClass: top -cn: activemq -dc: activemq - -dn: ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: organizationalUnit -objectClass: top -ou: ActiveMQ - -dn: ou=Services,dc=activemq,dc=apache,dc=org -ou: Services -objectClass: organizationalUnit -objectClass: top - -dn: cn=mqbroker,ou=Services,dc=activemq,dc=apache,dc=org -cn: mqbroker -objectClass: organizationalRole -objectClass: top -objectClass: simpleSecurityObject -userPassword: {SSHA}YvMAkkd66cDecNoejo8jnw5uUUBziyl0 -description: Bind user for MQ broker - - -################### -## Define groups ## -################### - - -dn: ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: organizationalUnit -objectClass: top -ou: Group - -dn: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: admins -member: uid=admin -objectClass: groupOfNames -objectClass: top - -dn: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: users -member: uid=jdoe -objectClass: groupOfNames -objectClass: top - - -################## -## Define users ## -################## - - -dn: ou=User,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: organizationalUnit -objectClass: top -ou: User - -dn: uid=admin,ou=User,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -uid: admin -userPassword: {SSHA}YvMAkkd66cDecNoejo8jnw5uUUBziyl0 -objectclass: uidObject -objectclass: organizationalPerson -objectclass: person -objectclass: top -cn: Admin -sn: Admin - - -dn: uid=jdoe,ou=User,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -uid: jdoe -userPassword: {SSHA}YvMAkkd66cDecNoejo8jnw5uUUBziyl0 -objectclass: uidObject -objectclass: organizationalPerson -objectclass: person -objectclass: top -cn: Jane Doe -sn: Doe - - -######################### -## Define destinations ## -######################### - -dn: ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: organizationalUnit -objectClass: top -ou: Destination - -dn: ou=Topic,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: organizationalUnit -objectClass: top -ou: Topic - -dn: ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: organizationalUnit -objectClass: top -ou: Queue - -## TEST.FOO - -dn: cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: TEST.FOO -description: A queue -objectClass: applicationProcess -objectClass: top - -dn: cn=admin,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: admin -description: Admin privilege group, members are roles -member: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: groupOfNames -objectClass: top - -dn: cn=read,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: read -member: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: write -objectClass: groupOfNames -objectClass: top -member: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org - -## TEST.FOOBAR - -dn: cn=TEST.FOOBAR,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: TEST.BAR -description: A queue -objectClass: applicationProcess -objectClass: top - -dn: cn=admin,cn=TEST.FOOBAR,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: admin -description: Admin privilege group, members are roles -member: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: groupOfNames -objectClass: top - -dn: cn=read,cn=TEST.FOOBAR,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: read -member: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: uid=jdoe,ou=User,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=notthere,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=TEST.FOOBAR,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: write -objectClass: groupOfNames -objectClass: top -member: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: uid=jdoe,ou=User,ou=ActiveMQ,dc=activemq,dc=apache,dc=org - -## FOO.> - -dn: cn=FOO.$,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: FOO.$ -description: A queue -objectClass: applicationProcess -objectClass: top - -dn: cn=admin,cn=FOO.$,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: admin -description: Admin privilege group, members are roles -member: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: groupOfNames -objectClass: top - -dn: cn=read,cn=FOO.$,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: read -member: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=FOO.$,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: write -objectClass: groupOfNames -objectClass: top -member: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org - -## BAR.* - -dn: cn=BAR.*,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: BAR.* -description: A queue -objectClass: applicationProcess -objectClass: top - -dn: cn=admin,cn=BAR.*,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: admin -description: Admin privilege group, members are roles -member: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: groupOfNames -objectClass: top - -dn: cn=read,cn=BAR.*,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: read -member: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=BAR.*,ou=Queue,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: write -objectClass: groupOfNames -objectClass: top -member: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org - -####################### -## Define advisories ## -####################### - -dn: cn=ActiveMQ.Advisory.$,ou=Topic,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: ActiveMQ.Advisory.$ -objectClass: applicationProcess -objectClass: top -description: Advisory topics - -dn: cn=read,cn=ActiveMQ.Advisory.$,ou=Topic,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: read -member: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=ActiveMQ.Advisory.$,ou=Topic,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: write -member: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: groupOfNames -objectClass: top - -dn: cn=admin,cn=ActiveMQ.Advisory.$,ou=Topic,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: admin -member: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: groupOfNames -objectClass: top - -###################### -## Define temporary ## -###################### - -dn: ou=Temp,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: organizationalUnit -objectClass: top -ou: Temp - -dn: cn=read,ou=Temp,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: read -member: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: groupOfNames -objectClass: top - -dn: cn=write,ou=Temp,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: write -member: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: groupOfNames -objectClass: top - -dn: cn=admin,ou=Temp,ou=Destination,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -cn: admin -member: cn=admins,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -member: cn=users,ou=Group,ou=ActiveMQ,dc=activemq,dc=apache,dc=org -objectClass: groupOfNames -objectClass: top - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap.xml deleted file mode 100644 index 1c34783e9e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-openldap.xml +++ /dev/null @@ -1,64 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-sslcontext.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-sslcontext.xml deleted file mode 100644 index 2297b2c940..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq-sslcontext.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq.ldif b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq.ldif deleted file mode 100644 index e9d1e42dc7..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/activemq.ldif +++ /dev/null @@ -1,241 +0,0 @@ -## --------------------------------------------------------------------------- -## Licensed to the Apache Software Foundation (ASF) under one or more -## contributor license agreements. See the NOTICE file distributed with -## this work for additional information regarding copyright ownership. -## The ASF licenses this file to You under the Apache License, Version 2.0 -## (the "License"); you may not use this file except in compliance with -## the License. You may obtain a copy of the License at -## -## http://www.apache.org/licenses/LICENSE-2.0 -## -## Unless required by applicable law or agreed to in writing, software -## distributed under the License is distributed on an "AS IS" BASIS, -## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -## See the License for the specific language governing permissions and -## limitations under the License. -## --------------------------------------------------------------------------- - - -########################## -## Define basic objects ## -########################## - -# Uncomment if adding to open ldap -#dn: ou=system -#objectclass: organizationalUnit -#objectclass: top -#ou: system - -dn: ou=ActiveMQ,ou=system -objectClass: organizationalUnit -objectClass: top -ou: ActiveMQ - -dn: ou=Services,ou=system -ou: Services -objectClass: organizationalUnit -objectClass: top - -dn: cn=mqbroker,ou=Services,ou=system -cn: mqbroker -objectClass: organizationalRole -objectClass: top -objectClass: simpleSecurityObject -userPassword: {SSHA}YvMAkkd66cDecNoejo8jnw5uUUBziyl0 -description: Bind user for MQ broker - - -################### -## Define groups ## -################### - - -dn: ou=Group,ou=ActiveMQ,ou=system -objectClass: organizationalUnit -objectClass: top -ou: Group - -dn: cn=admins,ou=Group,ou=ActiveMQ,ou=system -cn: admins -member: uid=admin -objectClass: groupOfNames -objectClass: top - -dn: cn=users,ou=Group,ou=ActiveMQ,ou=system -cn: users -member: uid=jdoe -objectClass: groupOfNames -objectClass: top - - -################## -## Define users ## -################## - - -dn: ou=User,ou=ActiveMQ,ou=system -objectClass: organizationalUnit -objectClass: top -ou: User - -dn: uid=admin,ou=User,ou=ActiveMQ,ou=system -uid: admin -userPassword: {SSHA}YvMAkkd66cDecNoejo8jnw5uUUBziyl0 -objectClass: account -objectClass: simpleSecurityObject -objectClass: top - - -dn: uid=jdoe,ou=User,ou=ActiveMQ,ou=system -uid: jdoe -userPassword: {SSHA}YvMAkkd66cDecNoejo8jnw5uUUBziyl0 -objectclass: inetOrgPerson -objectclass: organizationalPerson -objectclass: person -objectclass: top -cn: Jane Doe -sn: Doe - - -######################### -## Define destinations ## -######################### - -dn: ou=Destination,ou=ActiveMQ,ou=system -objectClass: organizationalUnit -objectClass: top -ou: Destination - -dn: ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -objectClass: organizationalUnit -objectClass: top -ou: Topic - -dn: ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -objectClass: organizationalUnit -objectClass: top -ou: Queue - -## TEST.FOO - -dn: cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: TEST.FOO -description: A queue -objectClass: applicationProcess -objectClass: top - -dn: cn=admin,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: admin -description: Admin privilege group, members are roles -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=read,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: read -member: cn=users -member: cn=admins -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=TEST.FOO,ou=Queue,ou=Destination,ou=ActiveMQ,ou=system -cn: write -objectClass: groupOfNames -objectClass: top -member: cn=users -member: cn=admins - -## TEST.BAR - -dn: cn=TEST.BAR,ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -cn: TEST.BAR -description: A topic -objectClass: applicationProcess -objectClass: top - -dn: cn=admin,cn=TEST.BAR,ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -cn: admin -description: Admin privilege group, members are roles -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=read,cn=TEST.BAR,ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -cn: read -member: cn=users -member: cn=admins -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=TEST.BAR,ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -cn: write -objectClass: groupOfNames -objectClass: top -member: cn=users -member: cn=admins - - -####################### -## Define advisories ## -####################### - -dn: cn=ActiveMQ.Advisory,ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -cn: ActiveMQ.Advisory -objectClass: applicationProcess -objectClass: top -description: Advisory topics - -dn: cn=read,cn=ActiveMQ.Advisory,ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -cn: read -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=ActiveMQ.Advisory,ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -cn: write -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=admin,cn=ActiveMQ.Advisory,ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -cn: admin -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -###################### -## Define temporary ## -###################### - -dn: cn=ActiveMQ.Temp,ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -cn: ActiveMQ.Temp -objectClass: applicationProcess -objectClass: top -description: Temporary destinations - -dn: cn=read,cn=ActiveMQ.Temp,ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -cn: read -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=write,cn=ActiveMQ.Temp,ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -cn: write -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - -dn: cn=admin,cn=ActiveMQ.Temp,ou=Topic,ou=Destination,ou=ActiveMQ,ou=system -cn: admin -member: cn=admins -member: cn=users -objectClass: groupOfNames -objectClass: top - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/broker1.ks b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/broker1.ks deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/broker1.ts b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/broker1.ts deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/broker1.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/broker1.xml deleted file mode 100644 index 190f701c5a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/broker1.xml +++ /dev/null @@ -1,72 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/broker2.ks b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/broker2.ks deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/broker2.ts b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/broker2.ts deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/broker2.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/broker2.xml deleted file mode 100644 index 946b04dfe3..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/broker2.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/client.ks b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/client.ks deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/client.ts b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/client.ts deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/dos-broker.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/dos-broker.xml deleted file mode 100644 index beffe49dd6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/dos-broker.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/groups.properties b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/groups.properties deleted file mode 100644 index 0898ea4c90..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/groups.properties +++ /dev/null @@ -1,21 +0,0 @@ -## --------------------------------------------------------------------------- -## Licensed to the Apache Software Foundation (ASF) under one or more -## contributor license agreements. See the NOTICE file distributed with -## this work for additional information regarding copyright ownership. -## The ASF licenses this file to You under the Apache License, Version 2.0 -## (the "License"); you may not use this file except in compliance with -## the License. You may obtain a copy of the License at -## -## http://www.apache.org/licenses/LICENSE-2.0 -## -## Unless required by applicable law or agreed to in writing, software -## distributed under the License is distributed on an "AS IS" BASIS, -## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -## See the License for the specific language governing permissions and -## limitations under the License. -## --------------------------------------------------------------------------- - -admins=system,sslclient,client,broker1,broker2 -tempDestinationAdmins=system,user,sslclient,client,broker1,broker2 -users=system,user,sslclient,client,broker1,broker2 -guests=guest diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/jaas-broker-guest-no-creds-only.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/jaas-broker-guest-no-creds-only.xml deleted file mode 100644 index 6ad1e72c2f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/jaas-broker-guest-no-creds-only.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/jaas-broker-guest.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/jaas-broker-guest.xml deleted file mode 100644 index c8474a349e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/jaas-broker-guest.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/jaas-broker.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/jaas-broker.xml deleted file mode 100644 index c36fec53e6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/jaas-broker.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/ldap-spring.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/ldap-spring.xml deleted file mode 100644 index aa6b086c64..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/ldap-spring.xml +++ /dev/null @@ -1,213 +0,0 @@ - - - - - - - - - - simple - uid=admin,ou=system - secret - - - - - - - - - - - - example.com - - - - - - - - - - - - - - false - false - - - - - - - - - - - - - - - - - - - - - - - example - dc=example,dc=com - - - dc - ou - objectClass - krb5PrincipalName - uid - - - - - objectClass: top - objectClass: domain - objectClass: extensibleObject - dc: example - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/simple-anonymous-broker.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/simple-anonymous-broker.xml deleted file mode 100644 index b9ebb53147..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/simple-anonymous-broker.xml +++ /dev/null @@ -1,91 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/simple-auth-broker.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/simple-auth-broker.xml deleted file mode 100644 index b6827283a8..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/simple-auth-broker.xml +++ /dev/null @@ -1,99 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/simple-auth-separator.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/simple-auth-separator.xml deleted file mode 100644 index 65ed69131f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/simple-auth-separator.xml +++ /dev/null @@ -1,100 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/sslcontext-client.ts b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/sslcontext-client.ts deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/sslcontext-keystore.ks b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/sslcontext-keystore.ks deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/users.properties b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/users.properties deleted file mode 100644 index cf72413658..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/users.properties +++ /dev/null @@ -1,21 +0,0 @@ -## --------------------------------------------------------------------------- -## Licensed to the Apache Software Foundation (ASF) under one or more -## contributor license agreements. See the NOTICE file distributed with -## this work for additional information regarding copyright ownership. -## The ASF licenses this file to You under the Apache License, Version 2.0 -## (the "License"); you may not use this file except in compliance with -## the License. You may obtain a copy of the License at -## -## http://www.apache.org/licenses/LICENSE-2.0 -## -## Unless required by applicable law or agreed to in writing, software -## distributed under the License is distributed on an "AS IS" BASIS, -## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -## See the License for the specific language governing permissions and -## limitations under the License. -## --------------------------------------------------------------------------- - -system=manager -user=password -guest=password -sslclient=CN=localhost, OU=activemq.org, O=activemq.org, L=LA, ST=CA, C=US \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/users1.properties b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/users1.properties deleted file mode 100644 index 14cb896047..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/users1.properties +++ /dev/null @@ -1,19 +0,0 @@ -## --------------------------------------------------------------------------- -## Licensed to the Apache Software Foundation (ASF) under one or more -## contributor license agreements. See the NOTICE file distributed with -## this work for additional information regarding copyright ownership. -## The ASF licenses this file to You under the Apache License, Version 2.0 -## (the "License"); you may not use this file except in compliance with -## the License. You may obtain a copy of the License at -## -## http://www.apache.org/licenses/LICENSE-2.0 -## -## Unless required by applicable law or agreed to in writing, software -## distributed under the License is distributed on an "AS IS" BASIS, -## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -## See the License for the specific language governing permissions and -## limitations under the License. -## --------------------------------------------------------------------------- - -client=CN=client, OU=activemq, O=apache -broker2=CN=broker2, OU=activemq, O=apache \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/users2.properties b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/users2.properties deleted file mode 100644 index c13864dff6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/security/users2.properties +++ /dev/null @@ -1,19 +0,0 @@ -## --------------------------------------------------------------------------- -## Licensed to the Apache Software Foundation (ASF) under one or more -## contributor license agreements. See the NOTICE file distributed with -## this work for additional information regarding copyright ownership. -## The ASF licenses this file to You under the Apache License, Version 2.0 -## (the "License"); you may not use this file except in compliance with -## the License. You may obtain a copy of the License at -## -## http://www.apache.org/licenses/LICENSE-2.0 -## -## Unless required by applicable law or agreed to in writing, software -## distributed under the License is distributed on an "AS IS" BASIS, -## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -## See the License for the specific language governing permissions and -## limitations under the License. -## --------------------------------------------------------------------------- - -client=CN=client, OU=activemq, O=apache -broker1=CN=broker1, OU=activemq, O=apache \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/SelectorParserTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/SelectorParserTest.java deleted file mode 100644 index bb0d2c4278..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/SelectorParserTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.selector; - -import javax.jms.InvalidSelectorException; - -import junit.framework.TestCase; - -import org.apache.activemq.filter.BooleanExpression; -import org.apache.activemq.filter.BooleanFunctionCallExpr; -import org.apache.activemq.filter.ComparisonExpression; -import org.apache.activemq.filter.Expression; -import org.apache.activemq.filter.LogicExpression; -import org.apache.activemq.filter.PropertyExpression; -import org.apache.activemq.filter.XPathExpression; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class SelectorParserTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(SelectorParserTest.class); - - public void testFunctionCall() throws Exception { - Object filter = parse("REGEX('sales.*', group)"); - assertTrue("expected type", filter instanceof BooleanFunctionCallExpr); - LOG.info("function exp:" + filter); - - // non existent function - try { - parse("DoesNotExist('sales.*', group)"); - fail("expect ex on non existent function"); - } catch (InvalidSelectorException expected) { - } - - } - - public void testParseXPath() throws Exception { - BooleanExpression filter = parse("XPATH '//title[@lang=''eng'']'"); - assertTrue("Created XPath expression", filter instanceof XPathExpression); - LOG.info("Expression: " + filter); - } - - public void testParseWithParensAround() throws Exception { - String[] values = {"x = 1 and y = 2", "(x = 1) and (y = 2)", "((x = 1) and (y = 2))"}; - - for (int i = 0; i < values.length; i++) { - String value = values[i]; - LOG.info("Parsing: " + value); - - BooleanExpression andExpression = parse(value); - assertTrue("Created LogicExpression expression", andExpression instanceof LogicExpression); - LogicExpression logicExpression = (LogicExpression) andExpression; - Expression left = logicExpression.getLeft(); - Expression right = logicExpression.getRight(); - - assertTrue("Left is a binary filter", left instanceof ComparisonExpression); - assertTrue("Right is a binary filter", right instanceof ComparisonExpression); - ComparisonExpression leftCompare = (ComparisonExpression) left; - ComparisonExpression rightCompare = (ComparisonExpression) right; - assertPropertyExpression("left", leftCompare.getLeft(), "x"); - assertPropertyExpression("right", rightCompare.getLeft(), "y"); - } - } - - protected void assertPropertyExpression(String message, Expression expression, String expected) { - assertTrue(message + ". Must be PropertyExpression", expression instanceof PropertyExpression); - PropertyExpression propExp = (PropertyExpression) expression; - assertEquals(message + ". Property name", expected, propExp.getName()); - } - - protected BooleanExpression parse(String text) throws Exception { - return SelectorParser.parse(text); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/SelectorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/SelectorTest.java deleted file mode 100644 index c2e88f797f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/SelectorTest.java +++ /dev/null @@ -1,394 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.selector; - -import javax.jms.InvalidSelectorException; -import javax.jms.JMSException; -import javax.jms.Message; - -import junit.framework.TestCase; - -import org.apache.activemq.command.ActiveMQMessage; -import org.apache.activemq.command.ActiveMQTextMessage; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.filter.BooleanExpression; -import org.apache.activemq.filter.MessageEvaluationContext; - -/** - * - */ -public class SelectorTest extends TestCase { - - public void testBooleanSelector() throws Exception { - Message message = createMessage(); - - assertSelector(message, "(trueProp OR falseProp) AND trueProp", true); - assertSelector(message, "(trueProp OR falseProp) AND falseProp", false); - assertSelector(message, "trueProp", true); - - } - - public void testXPathSelectors() throws Exception { - ActiveMQTextMessage message = new ActiveMQTextMessage(); - - message.setJMSType("xml"); - message.setText("b"); - - assertSelector(message, "XPATH 'root/a'", true); - assertSelector(message, "XPATH '//root/b'", true); - assertSelector(message, "XPATH 'root/c'", false); - assertSelector(message, "XPATH '//root/b/text()=\"b\"'", true); - assertSelector(message, "XPATH '//root/b=\"b\"'", true); - assertSelector(message, "XPATH '//root/b=\"c\"'", false); - assertSelector(message, "XPATH '//root/b!=\"c\"'", true); - - assertSelector(message, "XPATH '//root/*[@key=''second'']'", true); - assertSelector(message, "XPATH '//root/*[@key=''third'']'", false); - assertSelector(message, "XPATH '//root/a[@key=''first'']'", true); - assertSelector(message, "XPATH '//root/a[@num=1]'", true); - assertSelector(message, "XPATH '//root/a[@key=''second'']'", false); - - assertSelector(message, "XPATH '/root/*[@key=''first'' or @key=''third'']'", true); - assertSelector(message, "XPATH '//root/*[@key=''third'' or @key=''forth'']'", false); - - assertSelector(message, "XPATH '/root/b=''b'' and /root/b[@key=''second'']'", true); - assertSelector(message, "XPATH '/root/b=''b'' and /root/b[@key=''first'']'", false); - - assertSelector(message, "XPATH 'not(//root/a)'", false); - assertSelector(message, "XPATH 'not(//root/c)'", true); - assertSelector(message, "XPATH '//root/a[not(@key=''first'')]'", false); - assertSelector(message, "XPATH '//root/a[not(not(@key=''first''))]'", true); - - assertSelector(message, "XPATH 'string(//root/b)'", true); - assertSelector(message, "XPATH 'string(//root/a)'", false); - - assertSelector(message, "XPATH 'sum(//@num) < 10'", true); - assertSelector(message, "XPATH 'sum(//@num) > 10'", false); - - assertSelector(message, "XPATH '//root/a[@num > 1]'", false); - assertSelector(message, "XPATH '//root/b[@num > 1]'", true); - - } - - public void testJMSPropertySelectors() throws Exception { - Message message = createMessage(); - message.setJMSType("selector-test"); - message.setJMSMessageID("id:test:1:1:1:1"); - - assertSelector(message, "JMSType = 'selector-test'", true); - assertSelector(message, "JMSType = 'crap'", false); - - assertSelector(message, "JMSMessageID = 'id:test:1:1:1:1'", true); - assertSelector(message, "JMSMessageID = 'id:not-test:1:1:1:1'", false); - - message = createMessage(); - message.setJMSType("1001"); - - assertSelector(message, "JMSType='1001'", true); - assertSelector(message, "JMSType='1001' OR JMSType='1002'", true); - assertSelector(message, "JMSType = 'crap'", false); - } - - public void testBasicSelectors() throws Exception { - Message message = createMessage(); - - assertSelector(message, "name = 'James'", true); - assertSelector(message, "rank > 100", true); - assertSelector(message, "rank >= 123", true); - assertSelector(message, "rank >= 124", false); - - } - - public void testPropertyTypes() throws Exception { - Message message = createMessage(); - assertSelector(message, "byteProp = 123", true); - assertSelector(message, "byteProp = 10", false); - assertSelector(message, "byteProp2 = 33", true); - assertSelector(message, "byteProp2 = 10", false); - - assertSelector(message, "shortProp = 123", true); - assertSelector(message, "shortProp = 10", false); - - assertSelector(message, "shortProp = 123", true); - assertSelector(message, "shortProp = 10", false); - - assertSelector(message, "intProp = 123", true); - assertSelector(message, "intProp = 10", false); - - assertSelector(message, "longProp = 123", true); - assertSelector(message, "longProp = 10", false); - - assertSelector(message, "floatProp = 123", true); - assertSelector(message, "floatProp = 10", false); - - assertSelector(message, "doubleProp = 123", true); - assertSelector(message, "doubleProp = 10", false); - } - - public void testAndSelectors() throws Exception { - Message message = createMessage(); - - assertSelector(message, "name = 'James' and rank < 200", true); - assertSelector(message, "name = 'James' and rank > 200", false); - assertSelector(message, "name = 'Foo' and rank < 200", false); - assertSelector(message, "unknown = 'Foo' and anotherUnknown < 200", false); - } - - public void testOrSelectors() throws Exception { - Message message = createMessage(); - - assertSelector(message, "name = 'James' or rank < 200", true); - assertSelector(message, "name = 'James' or rank > 200", true); - assertSelector(message, "name = 'Foo' or rank < 200", true); - assertSelector(message, "name = 'Foo' or rank > 200", false); - assertSelector(message, "unknown = 'Foo' or anotherUnknown < 200", false); - } - - public void testPlus() throws Exception { - Message message = createMessage(); - - assertSelector(message, "rank + 2 = 125", true); - assertSelector(message, "(rank + 2) = 125", true); - assertSelector(message, "125 = (rank + 2)", true); - assertSelector(message, "rank + version = 125", true); - assertSelector(message, "rank + 2 < 124", false); - assertSelector(message, "name + '!' = 'James!'", true); - } - - public void testMinus() throws Exception { - Message message = createMessage(); - - assertSelector(message, "rank - 2 = 121", true); - assertSelector(message, "rank - version = 121", true); - assertSelector(message, "rank - 2 > 122", false); - } - - public void testMultiply() throws Exception { - Message message = createMessage(); - - assertSelector(message, "rank * 2 = 246", true); - assertSelector(message, "rank * version = 246", true); - assertSelector(message, "rank * 2 < 130", false); - } - - public void testDivide() throws Exception { - Message message = createMessage(); - - assertSelector(message, "rank / version = 61.5", true); - assertSelector(message, "rank / 3 > 100.0", false); - assertSelector(message, "rank / 3 > 100", false); - assertSelector(message, "version / 2 = 1", true); - - } - - public void testBetween() throws Exception { - Message message = createMessage(); - - assertSelector(message, "rank between 100 and 150", true); - assertSelector(message, "rank between 10 and 120", false); - } - - public void testIn() throws Exception { - Message message = createMessage(); - - assertSelector(message, "name in ('James', 'Bob', 'Gromit')", true); - assertSelector(message, "name in ('Bob', 'James', 'Gromit')", true); - assertSelector(message, "name in ('Gromit', 'Bob', 'James')", true); - - assertSelector(message, "name in ('Gromit', 'Bob', 'Cheddar')", false); - assertSelector(message, "name not in ('Gromit', 'Bob', 'Cheddar')", true); - } - - public void testIsNull() throws Exception { - Message message = createMessage(); - - assertSelector(message, "dummy is null", true); - assertSelector(message, "dummy is not null", false); - assertSelector(message, "name is not null", true); - assertSelector(message, "name is null", false); - } - - public void testLike() throws Exception { - Message message = createMessage(); - message.setStringProperty("modelClassId", "com.whatever.something.foo.bar"); - message.setStringProperty("modelInstanceId", "170"); - message.setStringProperty("modelRequestError", "abc"); - message.setStringProperty("modelCorrelatedClientId", "whatever"); - - assertSelector(message, "modelClassId LIKE 'com.whatever.something.%' AND modelInstanceId = '170' AND (modelRequestError IS NULL OR modelCorrelatedClientId = 'whatever')", true); - - message.setStringProperty("modelCorrelatedClientId", "shouldFailNow"); - - assertSelector(message, "modelClassId LIKE 'com.whatever.something.%' AND modelInstanceId = '170' AND (modelRequestError IS NULL OR modelCorrelatedClientId = 'whatever')", false); - - message = createMessage(); - message.setStringProperty("modelClassId", "com.whatever.something.foo.bar"); - message.setStringProperty("modelInstanceId", "170"); - message.setStringProperty("modelCorrelatedClientId", "shouldNotMatch"); - - assertSelector(message, "modelClassId LIKE 'com.whatever.something.%' AND modelInstanceId = '170' AND (modelRequestError IS NULL OR modelCorrelatedClientId = 'whatever')", true); - } - - /** - * Test cases from Mats Henricson - */ - public void testMatsHenricsonUseCases() throws Exception { - Message message = createMessage(); - assertSelector(message, "SessionserverId=1870414179", false); - - message.setLongProperty("SessionserverId", 1870414179); - assertSelector(message, "SessionserverId=1870414179", true); - - message.setLongProperty("SessionserverId", 1234); - assertSelector(message, "SessionserverId=1870414179", false); - - assertSelector(message, "Command NOT IN ('MirrorLobbyRequest', 'MirrorLobbyReply')", false); - - message.setStringProperty("Command", "Cheese"); - assertSelector(message, "Command NOT IN ('MirrorLobbyRequest', 'MirrorLobbyReply')", true); - - message.setStringProperty("Command", "MirrorLobbyRequest"); - assertSelector(message, "Command NOT IN ('MirrorLobbyRequest', 'MirrorLobbyReply')", false); - message.setStringProperty("Command", "MirrorLobbyReply"); - assertSelector(message, "Command NOT IN ('MirrorLobbyRequest', 'MirrorLobbyReply')", false); - } - - public void testFloatComparisons() throws Exception { - Message message = createMessage(); - - assertSelector(message, "1.0 < 1.1", true); - assertSelector(message, "-1.1 < 1.0", true); - assertSelector(message, "1.0E1 < 1.1E1", true); - assertSelector(message, "-1.1E1 < 1.0E1", true); - - assertSelector(message, "1. < 1.1", true); - assertSelector(message, "-1.1 < 1.", true); - assertSelector(message, "1.E1 < 1.1E1", true); - assertSelector(message, "-1.1E1 < 1.E1", true); - - assertSelector(message, ".1 < .5", true); - assertSelector(message, "-.5 < .1", true); - assertSelector(message, ".1E1 < .5E1", true); - assertSelector(message, "-.5E1 < .1E1", true); - - assertSelector(message, "4E10 < 5E10", true); - assertSelector(message, "5E8 < 5E10", true); - assertSelector(message, "-4E10 < 2E10", true); - assertSelector(message, "-5E8 < 2E2", true); - assertSelector(message, "4E+10 < 5E+10", true); - assertSelector(message, "4E-10 < 5E-10", true); - } - - public void testStringQuoteParsing() throws Exception { - Message message = createMessage(); - assertSelector(message, "quote = '''In God We Trust'''", true); - } - - public void testLikeComparisons() throws Exception { - Message message = createMessage(); - - assertSelector(message, "quote LIKE '''In G_d We Trust'''", true); - assertSelector(message, "quote LIKE '''In Gd_ We Trust'''", false); - assertSelector(message, "quote NOT LIKE '''In G_d We Trust'''", false); - assertSelector(message, "quote NOT LIKE '''In Gd_ We Trust'''", true); - - assertSelector(message, "foo LIKE '%oo'", true); - assertSelector(message, "foo LIKE '%ar'", false); - assertSelector(message, "foo NOT LIKE '%oo'", false); - assertSelector(message, "foo NOT LIKE '%ar'", true); - - assertSelector(message, "foo LIKE '!_%' ESCAPE '!'", true); - assertSelector(message, "quote LIKE '!_%' ESCAPE '!'", false); - assertSelector(message, "foo NOT LIKE '!_%' ESCAPE '!'", false); - assertSelector(message, "quote NOT LIKE '!_%' ESCAPE '!'", true); - - assertSelector(message, "punctuation LIKE '!#$&()*+,-./:;<=>?@[\\]^`{|}~'", true); - } - - public void testInvalidSelector() throws Exception { - Message message = createMessage(); - assertInvalidSelector(message, "3+5"); - assertInvalidSelector(message, "True AND 3+5"); - assertInvalidSelector(message, "=TEST 'test'"); - } - - public void testFunctionSelector() throws Exception { - Message message = createMessage(); - assertSelector(message, "REGEX('1870414179', SessionserverId)", false); - message.setLongProperty("SessionserverId", 1870414179); - assertSelector(message, "REGEX('1870414179', SessionserverId)", true); - assertSelector(message, "REGEX('[0-9]*', SessionserverId)", true); - assertSelector(message, "REGEX('^[1-8]*$', SessionserverId)", false); - assertSelector(message, "REGEX('^[1-8]*$', SessionserverId)", false); - - assertSelector(message, "INLIST(SPLIT('Tom,Dick,George',','), name)", false); - assertSelector(message, "INLIST(SPLIT('Tom,James,George',','), name)", true); - - assertSelector(message, "INLIST(MAKELIST('Tom','Dick','George'), name)", false); - assertSelector(message, "INLIST(MAKELIST('Tom','James','George'), name)", true); - - assertSelector(message, "REGEX('connection1111', REPLACE(JMSMessageID,':',''))", true); - } - - protected Message createMessage() throws JMSException { - Message message = createMessage("FOO.BAR"); - message.setJMSType("selector-test"); - message.setJMSMessageID("connection:1:1:1:1"); - message.setObjectProperty("name", "James"); - message.setObjectProperty("location", "London"); - - message.setByteProperty("byteProp", (byte) 123); - message.setByteProperty("byteProp2", (byte) 33); - message.setShortProperty("shortProp", (short) 123); - message.setIntProperty("intProp", 123); - message.setLongProperty("longProp", 123); - message.setFloatProperty("floatProp", 123); - message.setDoubleProperty("doubleProp", 123); - - message.setIntProperty("rank", 123); - message.setIntProperty("version", 2); - message.setStringProperty("quote", "'In God We Trust'"); - message.setStringProperty("foo", "_foo"); - message.setStringProperty("punctuation", "!#$&()*+,-./:;<=>?@[\\]^`{|}~"); - message.setBooleanProperty("trueProp", true); - message.setBooleanProperty("falseProp", false); - return message; - } - - protected void assertInvalidSelector(Message message, String text) throws JMSException { - try { - SelectorParser.parse(text); - fail("Created a valid selector"); - } catch (InvalidSelectorException e) { - } - } - - protected void assertSelector(Message message, String text, boolean expected) throws JMSException { - BooleanExpression selector = SelectorParser.parse(text); - assertTrue("Created a valid selector", selector != null); - MessageEvaluationContext context = new MessageEvaluationContext(); - context.setMessageReference((org.apache.activemq.command.Message) message); - boolean value = selector.matches(context); - assertEquals("Selector for: " + text, expected, value); - } - - protected Message createMessage(String subject) throws JMSException { - ActiveMQMessage message = new ActiveMQMessage(); - message.setJMSDestination(new ActiveMQTopic(subject)); - return message; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/UnknownHandlingSelectorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/UnknownHandlingSelectorTest.java deleted file mode 100644 index 32c5d1874c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/selector/UnknownHandlingSelectorTest.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.activemq.selector; - -import javax.jms.JMSException; -import javax.jms.Message; - -import org.apache.activemq.command.ActiveMQMessage; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.filter.BooleanExpression; -import org.apache.activemq.filter.MessageEvaluationContext; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class UnknownHandlingSelectorTest { - - private Message message; - - @Before - public void setUp() throws Exception { - message = new ActiveMQMessage(); - message.setJMSDestination(new ActiveMQTopic("FOO.BAR")); - message.setJMSType("selector-test"); - message.setJMSMessageID("connection:1:1:1:1"); - message.setBooleanProperty("trueProp", true); - message.setBooleanProperty("falseProp", false); - message.setObjectProperty("nullProp", null); - } - - /** - * | NOT - * +------+------ - * | T | F - * | F | T - * | U | U - * +------+------- - */ - @Test - public void notEvaluation() throws Exception { - assertSelector("not(trueProp)", false); - assertSelector("not(falseProp)", true); - assertSelector("not(unknownProp)", false); - } - - /** - * | AND | T | F | U - * +------+-------+-------+------- - * | T | T | F | U - * | F | F | F | F - * | U | U | F | U - * +------+-------+-------+------- - */ - @Test - public void andEvaluation() throws Exception { - assertSelectorEvaluatesToTrue("trueProp AND trueProp"); - assertSelectorEvaluatesToFalse("trueProp AND falseProp"); - assertSelectorEvaluatesToFalse("falseProp AND trueProp"); - assertSelectorEvaluatesToFalse("falseProp AND falseProp"); - assertSelectorEvaluatesToFalse("falseProp AND unknownProp"); - assertSelectorEvaluatesToFalse("unknownProp AND falseProp"); - assertSelectorEvaluatesToUnknown("trueProp AND unknownProp"); - assertSelectorEvaluatesToUnknown("unknownProp AND trueProp"); - assertSelectorEvaluatesToUnknown("unknownProp AND unknownProp"); - } - - /** - * | OR | T | F | U - * +------+-------+-------+-------- - * | T | T | T | T - * | F | T | F | U - * | U | T | U | U - * +------+-------+-------+------- - */ - @Test - public void orEvaluation() throws Exception { - assertSelectorEvaluatesToTrue("trueProp OR trueProp"); - assertSelectorEvaluatesToTrue("trueProp OR falseProp"); - assertSelectorEvaluatesToTrue("falseProp OR trueProp"); - assertSelectorEvaluatesToTrue("trueProp OR unknownProp"); - assertSelectorEvaluatesToTrue("unknownProp OR trueProp"); - assertSelectorEvaluatesToFalse("falseProp OR falseProp"); - assertSelectorEvaluatesToUnknown("falseProp OR unknownProp"); - assertSelectorEvaluatesToUnknown("unknownProp OR falseProp"); - assertSelectorEvaluatesToUnknown("unknownProp OR unknownProp"); - } - - @Test - public void comparisonWithUnknownShouldEvaluateToUnknown() throws Exception { - assertSelectorEvaluatesToUnknown("unknownProp = 0"); - assertSelectorEvaluatesToUnknown("unknownProp > 0"); - assertSelectorEvaluatesToUnknown("unknownProp >= 0"); - assertSelectorEvaluatesToUnknown("unknownProp < 0"); - assertSelectorEvaluatesToUnknown("unknownProp <= 0"); - assertSelectorEvaluatesToUnknown("unknownProp <> 0"); - assertSelectorEvaluatesToUnknown("unknownProp LIKE 'zero'"); - assertSelectorEvaluatesToUnknown("unknownProp NOT LIKE 'zero'"); - assertSelectorEvaluatesToUnknown("unknownProp IN ('zero')"); - assertSelectorEvaluatesToUnknown("unknownProp NOT IN ('zero')"); - assertSelectorEvaluatesToUnknown("unknownProp BETWEEN 1 AND 2"); - assertSelectorEvaluatesToUnknown("unknownProp NOT BETWEEN 1 AND 2"); - } - - @Test - public void comparisonWithNullPropShouldEvaluateToUnknown() throws Exception { - assertSelectorEvaluatesToUnknown("nullProp = 0"); - assertSelectorEvaluatesToUnknown("nullProp > 0"); - assertSelectorEvaluatesToUnknown("nullProp >= 0"); - assertSelectorEvaluatesToUnknown("nullProp < 0"); - assertSelectorEvaluatesToUnknown("nullProp <= 0"); - assertSelectorEvaluatesToUnknown("nullProp <> 0"); - assertSelectorEvaluatesToUnknown("nullProp LIKE 'zero'"); - assertSelectorEvaluatesToUnknown("nullProp NOT LIKE 'zero'"); - assertSelectorEvaluatesToUnknown("nullProp IN ('zero')"); - assertSelectorEvaluatesToUnknown("nullProp NOT IN ('zero')"); - assertSelectorEvaluatesToUnknown("nullProp BETWEEN 1 AND 2"); - assertSelectorEvaluatesToUnknown("nullProp NOT BETWEEN 1 AND 2"); - } - - @Test - public void isNullIsNotNull() throws Exception { - assertSelectorEvaluatesToTrue("unknownProp IS NULL"); - assertSelectorEvaluatesToTrue("nullProp IS NULL"); - assertSelectorEvaluatesToFalse("trueProp IS NULL"); - assertSelectorEvaluatesToFalse("unknownProp IS NOT NULL"); - assertSelectorEvaluatesToFalse("nullProp IS NOT NULL"); - assertSelectorEvaluatesToTrue("trueProp IS NOT NULL"); - } - - @Test - public void arithmeticWithNull() throws Exception { - assertSelectorEvaluatesToUnknown("-unknownProp = 0"); - assertSelectorEvaluatesToUnknown("+unknownProp = 0"); - assertSelectorEvaluatesToUnknown("unknownProp * 2 = 0"); - assertSelectorEvaluatesToUnknown("unknownProp / 2 = 0"); - assertSelectorEvaluatesToUnknown("unknownProp + 2 = 0"); - assertSelectorEvaluatesToUnknown("unknownProp - 2 = 0"); - } - - protected void assertSelectorEvaluatesToUnknown(String selector) throws JMSException { - assertSelector(selector, false); - assertSelector(not(selector), false); - } - - protected void assertSelectorEvaluatesToTrue(String selector) throws JMSException { - assertSelector(selector, true); - assertSelector(not(selector), false); - } - - protected void assertSelectorEvaluatesToFalse(String selector) throws JMSException { - assertSelector(selector, false); - assertSelector(not(selector), true); - } - - protected void assertSelector(String text, boolean matches) throws JMSException { - BooleanExpression selector = SelectorParser.parse(text); - assertTrue("Created a valid selector", selector != null); - MessageEvaluationContext context = new MessageEvaluationContext(); - context.setMessageReference((org.apache.activemq.command.Message) message); - boolean value = selector.matches(context); - assertEquals("Selector for: " + text, matches, value); - } - - private static String not(String selector) { - return "not(" + selector + ")"; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/ActiveMQConnectionFactoryFactoryBeanTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/ActiveMQConnectionFactoryFactoryBeanTest.java deleted file mode 100644 index 1b2c5cd77b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/ActiveMQConnectionFactoryFactoryBeanTest.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.activemq.spring; - -import java.util.Arrays; - -import junit.framework.TestCase; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class ActiveMQConnectionFactoryFactoryBeanTest extends TestCase { - - private static final transient Logger LOG = LoggerFactory.getLogger(ActiveMQConnectionFactoryFactoryBeanTest.class); - - private ActiveMQConnectionFactoryFactoryBean factory; - - public void testSingleTcpURL() throws Exception { - factory.setTcpHostAndPort("tcp://localhost:61616"); - assertCreatedURL("failover:(tcp://localhost:61616)"); - } - - public void testSingleTcpURLWithInactivityTimeout() throws Exception { - factory.setTcpHostAndPort("tcp://localhost:61616"); - factory.setMaxInactivityDuration(60000L); - assertCreatedURL("failover:(tcp://localhost:61616?wireFormat.maxInactivityDuration=60000)"); - } - - public void testSingleTcpURLWithInactivityTimeoutAndTcpNoDelay() throws Exception { - factory.setTcpHostAndPort("tcp://localhost:61616"); - factory.setMaxInactivityDuration(50000L); - factory.setTcpProperties("tcpNoDelayEnabled=true"); - assertCreatedURL("failover:(tcp://localhost:61616?wireFormat.maxInactivityDuration=50000&tcpNoDelayEnabled=true)"); - } - - public void testSingleTcpURLWithInactivityTimeoutAndMaxReconnectDelay() throws Exception { - factory.setTcpHostAndPort("tcp://localhost:61616"); - factory.setMaxInactivityDuration(60000L); - factory.setMaxReconnectDelay(50000L); - assertCreatedURL("failover:(tcp://localhost:61616?wireFormat.maxInactivityDuration=60000)?maxReconnectDelay=50000"); - } - - public void testSingleTcpURLWithInactivityTimeoutAndMaxReconnectDelayAndFailoverProperty() throws Exception { - factory.setTcpHostAndPort("tcp://localhost:61616"); - factory.setMaxInactivityDuration(40000L); - factory.setMaxReconnectDelay(30000L); - factory.setFailoverProperties("useExponentialBackOff=false"); - - assertCreatedURL("failover:(tcp://localhost:61616?wireFormat.maxInactivityDuration=40000)?maxReconnectDelay=30000&useExponentialBackOff=false"); - } - - public void testMultipleTcpURLsWithInactivityTimeoutAndMaxReconnectDelayAndFailoverProperty() throws Exception { - factory.setTcpHostAndPorts(Arrays.asList(new String[]{"tcp://localhost:61618", "tcp://foo:61619"})); - factory.setMaxInactivityDuration(40000L); - factory.setMaxReconnectDelay(30000L); - factory.setFailoverProperties("useExponentialBackOff=false"); - - assertCreatedURL("failover:(tcp://localhost:61618?wireFormat.maxInactivityDuration=40000,tcp://foo:61619?wireFormat.maxInactivityDuration=40000)?maxReconnectDelay=30000&useExponentialBackOff=false"); - } - - protected void assertCreatedURL(String expectedURL) throws Exception { - String url = factory.getBrokerURL(); - LOG.debug("Generated URL: " + url); - - assertEquals("URL", expectedURL, url); - Object value = factory.getObject(); - assertTrue("Value should be an ActiveMQConnectionFactory", value instanceof ActiveMQConnectionFactory); - ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory) value; - String brokerURL = connectionFactory.getBrokerURL(); - assertEquals("brokerURL", expectedURL, brokerURL); - } - - @Override - protected void setUp() throws Exception { - factory = new ActiveMQConnectionFactoryFactoryBean(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/ConsumerBean.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/ConsumerBean.java deleted file mode 100644 index ed721e7dc5..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/ConsumerBean.java +++ /dev/null @@ -1,168 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.spring; - -import javax.jms.Message; -import javax.jms.MessageListener; -import java.util.ArrayList; -import java.util.List; - -import org.junit.Assert; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ConsumerBean extends Assert implements MessageListener { - - private static final Logger LOG = LoggerFactory.getLogger(ConsumerBean.class); - private final List messages = new ArrayList<>(); - private boolean verbose; - - /** - * Constructor. - */ - public ConsumerBean() { - } - - /** - * @return all the messages on the list so far, clearing the buffer - */ - public List flushMessages() { - List answer = null; - synchronized (messages) { - answer = new ArrayList<>(messages); - messages.clear(); - } - return answer; - } - - /** - * Method implemented from MessageListener interface. - * - * @param message - */ - @Override - public void onMessage(Message message) { - synchronized (messages) { - messages.add(message); - if (verbose) { - LOG.info("Received: " + message); - } - messages.notifyAll(); - } - } - - /** - * Use to wait for a single message to arrive. - */ - public void waitForMessageToArrive() { - LOG.info("Waiting for message to arrive"); - - long start = System.currentTimeMillis(); - - synchronized (messages) { - try { - while (hasReceivedMessage()) { - messages.wait(4000); - } - } catch (InterruptedException e) { - LOG.info("Caught: " + e); - } - } - long end = System.currentTimeMillis() - start; - - LOG.info("End of wait for " + end + " millis"); - } - - /** - * Used to wait for a message to arrive given a particular message count. - * - * @param messageCount - */ - - public void waitForMessagesToArrive(int messageCount) { - waitForMessagesToArrive(messageCount, 120 * 1000); - } - - public void waitForMessagesToArrive(int messageCount, long maxWaitTime) { - long maxRemainingMessageCount = Math.max(0, messageCount - messages.size()); - LOG.info("Waiting for (" + maxRemainingMessageCount + ") message(s) to arrive"); - long start = System.currentTimeMillis(); - long endTime = start + maxWaitTime; - synchronized (messages) { - while (maxRemainingMessageCount > 0) { - try { - messages.wait(1000); - if (hasReceivedMessages(messageCount) || System.currentTimeMillis() > endTime) { - break; - } - } catch (InterruptedException e) { - LOG.info("Caught: " + e); - } - maxRemainingMessageCount = Math.max(0, messageCount - messages.size()); - } - } - long end = System.currentTimeMillis() - start; - LOG.info("End of wait for " + end + " millis"); - } - - public void assertMessagesArrived(int total) { - waitForMessagesToArrive(total); - synchronized (messages) { - int count = messages.size(); - - assertEquals("Messages received", total, count); - } - } - - public void assertMessagesArrived(int total, long maxWaitTime) { - waitForMessagesToArrive(total, maxWaitTime); - synchronized (messages) { - int count = messages.size(); - - assertEquals("Messages received", total, count); - } - } - - public boolean isVerbose() { - return verbose; - } - - public void setVerbose(boolean verbose) { - this.verbose = verbose; - } - - /** - * Identifies if the message is empty. - * - * @return - */ - protected boolean hasReceivedMessage() { - return messages.isEmpty(); - } - - /** - * Identifies if the message count has reached the total size of message. - * - * @param messageCount - * @return - */ - protected boolean hasReceivedMessages(int messageCount) { - synchronized (messages) { - return messages.size() >= messageCount; - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/Spring2XmlNamespacesTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/Spring2XmlNamespacesTest.java deleted file mode 100644 index 667323e86d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/Spring2XmlNamespacesTest.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.spring; - -public class Spring2XmlNamespacesTest extends SpringTestSupport { - - public void testUsingSpringXmlNamespacesWithPublicXsdLocation() throws Exception { - assertSenderConfig("spring-embedded-xbean.xml"); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/Spring2XmlNamespacesWithoutRemoteSchemaTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/Spring2XmlNamespacesWithoutRemoteSchemaTest.java deleted file mode 100644 index 3921ca6265..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/Spring2XmlNamespacesWithoutRemoteSchemaTest.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.spring; - -public class Spring2XmlNamespacesWithoutRemoteSchemaTest extends SpringTestSupport { - - public void testUsingSpring2NamespacesForANonExistingXsdDocument() throws Exception { - assertSenderConfig("spring-embedded-xbean-noversion.xml"); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringConsumer.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringConsumer.java deleted file mode 100644 index 5f3b6d13cc..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringConsumer.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.activemq.spring; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.Session; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.jms.core.JmsTemplate; - -public class SpringConsumer extends ConsumerBean implements MessageListener { - - private static final Logger LOG = LoggerFactory.getLogger(SpringConsumer.class); - private JmsTemplate template; - private String myId = "foo"; - private Destination destination; - private Connection connection; - private Session session; - private MessageConsumer consumer; - - public void start() throws JMSException { - String selector = "next = '" + myId + "'"; - - try { - ConnectionFactory factory = template.getConnectionFactory(); - final Connection c = connection = factory.createConnection(); - - // we might be a reusable connection in spring - // so lets only set the client ID once if its not set - synchronized (c) { - if (c.getClientID() == null) { - c.setClientID(myId); - } - } - - connection.start(); - - session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - consumer = session.createConsumer(destination, selector, false); - consumer.setMessageListener(this); - } catch (JMSException ex) { - LOG.error("", ex); - throw ex; - } - } - - public void stop() throws JMSException { - if (consumer != null) { - consumer.close(); - } - if (session != null) { - session.close(); - } - if (connection != null) { - connection.close(); - } - } - - @Override - public void onMessage(Message message) { - super.onMessage(message); - try { - message.acknowledge(); - } catch (JMSException e) { - LOG.error("Failed to acknowledge: " + e, e); - } - } - - // Properties - // ------------------------------------------------------------------------- - public Destination getDestination() { - return destination; - } - - public void setDestination(Destination destination) { - this.destination = destination; - } - - public String getMyId() { - return myId; - } - - public void setMyId(String myId) { - this.myId = myId; - } - - public JmsTemplate getTemplate() { - return template; - } - - public void setTemplate(JmsTemplate template) { - this.template = template; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringProducer.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringProducer.java deleted file mode 100644 index 07f23a3d2d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringProducer.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.activemq.spring; - -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.Session; -import javax.jms.TextMessage; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.jms.core.JmsTemplate; -import org.springframework.jms.core.MessageCreator; - -public class SpringProducer { - - private static final Logger LOG = LoggerFactory.getLogger(SpringProducer.class); - private JmsTemplate template; - private Destination destination; - private int messageCount = 10; - - public void start() throws JMSException { - for (int i = 0; i < messageCount; i++) { - final String text = "Text for message: " + i; - template.send(destination, new MessageCreator() { - @Override - public Message createMessage(Session session) throws JMSException { - LOG.info("Sending message: " + text); - TextMessage message = session.createTextMessage(text); - message.setStringProperty("next", "foo"); - return message; - } - }); - } - } - - public void stop() throws JMSException { - } - - // Properties - //------------------------------------------------------------------------- - - public JmsTemplate getTemplate() { - return template; - } - - public void setTemplate(JmsTemplate template) { - this.template = template; - } - - public int getMessageCount() { - return messageCount; - } - - public void setMessageCount(int messageCount) { - this.messageCount = messageCount; - } - - public Destination getDestination() { - return destination; - } - - public void setDestination(Destination destination) { - this.destination = destination; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringTest.java deleted file mode 100644 index f55544726f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringTest.java +++ /dev/null @@ -1,98 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.spring; - -import org.apache.activemq.broker.BrokerService; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class SpringTest extends SpringTestSupport { - - /** - * Uses ActiveMQConnectionFactory to create the connection context. - * Configuration file is /resources/spring.xml - * - * @throws Exception - */ - public void testSenderWithSpringXml() throws Exception { - String config = "spring.xml"; - assertSenderConfig(config); - } - - /** - * Spring configured test that uses ActiveMQConnectionFactory for - * connection context and ActiveMQQueue for destination. Configuration - * file is /resources/spring-queue.xml. - * - * @throws Exception - */ - public void testSenderWithSpringXmlAndQueue() throws Exception { - String config = "spring-queue.xml"; - assertSenderConfig(config); - } - - /** - * Spring configured test that uses JNDI. Configuration file is - * /resources/spring-jndi.xml. - * - * @throws Exception - */ - public void testSenderWithSpringXmlUsingJNDI() throws Exception { - String config = "spring-jndi.xml"; - assertSenderConfig(config); - } - - /** - * Spring configured test where in the connection context is set to use - * an embedded broker. Configuration file is /resources/spring-embedded.xml - * and /resources/activemq.xml. - * - * @throws Exception - */ - public void testSenderWithSpringXmlEmbeddedBrokerConfiguredViaXml() throws Exception { - String config = "spring-embedded.xml"; - assertSenderConfig(config); - } - - /** - * Spring configured test case that tests the remotely deployed xsd - * http://people.apache.org/repository/org.apache.activemq/xsds/activemq-core-4.1-SNAPSHOT.xsd - * - * @throws Exception - */ - public void testSenderWithSpringXmlUsingSpring2NamespacesWithEmbeddedBrokerConfiguredViaXml() throws Exception { - String config = "spring-embedded-xbean.xml"; - assertSenderConfig(config); - } - - /** - * Spring configured test case that tests the locally generated xsd - * - * @throws Exception - */ - public void testSenderWithSpringXmlUsingSpring2NamespacesWithEmbeddedBrokerConfiguredViaXmlUsingLocalXsd() throws Exception { - String config = "spring-embedded-xbean-local.xml"; - assertSenderConfig(config); - } - - public void testStartFalse() throws Exception { - String config = "spring-start-false.xml"; - Thread.currentThread().setContextClassLoader(SpringTest.class.getClassLoader()); - context = new ClassPathXmlApplicationContext(config); - BrokerService broker = context.getBean(BrokerService.class); - assertFalse("Broker is started", broker.isStarted()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringTestSupport.java deleted file mode 100644 index ecfeb0a511..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/spring/SpringTestSupport.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.spring; - -import javax.jms.Message; -import java.util.Iterator; -import java.util.List; - -import junit.framework.TestCase; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.support.AbstractApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * - */ -public class SpringTestSupport extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(SpringTest.class); - protected AbstractApplicationContext context; - protected SpringConsumer consumer; - protected SpringProducer producer; - - /** - * assert method that is used by all the test method to send and receive messages - * based on each spring configuration. - * - * @param config - * @throws Exception - */ - protected void assertSenderConfig(String config) throws Exception { - Thread.currentThread().setContextClassLoader(SpringTest.class.getClassLoader()); - context = new ClassPathXmlApplicationContext(config); - - consumer = (SpringConsumer) context.getBean("consumer"); - assertTrue("Found a valid consumer", consumer != null); - - consumer.start(); - - // Wait a little to drain any left over messages. - Thread.sleep(1000); - consumer.flushMessages(); - - producer = (SpringProducer) context.getBean("producer"); - assertTrue("Found a valid producer", producer != null); - - producer.start(); - - // lets sleep a little to give the JMS time to dispatch stuff - consumer.waitForMessagesToArrive(producer.getMessageCount()); - - // now lets check that the consumer has received some messages - List messages = consumer.flushMessages(); - LOG.info("Consumer has received messages...."); - for (Iterator iter = messages.iterator(); iter.hasNext(); ) { - Object message = iter.next(); - LOG.info("Received: " + message); - } - - assertEquals("Message count", producer.getMessageCount(), messages.size()); - } - - /** - * Clean up method. - * - * @throws Exception - */ - @Override - protected void tearDown() throws Exception { - if (consumer != null) { - consumer.stop(); - } - if (producer != null) { - producer.stop(); - } - - if (context != null) { - context.destroy(); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithEmbeddedBrokerAndUserIDTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithEmbeddedBrokerAndUserIDTest.java deleted file mode 100644 index e42dd85ae3..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithEmbeddedBrokerAndUserIDTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.test; - -import javax.jms.JMSException; -import javax.jms.Message; -import java.util.List; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class JmsTopicSendReceiveWithEmbeddedBrokerAndUserIDTest extends JmsTopicSendReceiveWithTwoConnectionsAndEmbeddedBrokerTest { - - private static final Logger LOG = LoggerFactory.getLogger(JmsTopicSendReceiveWithEmbeddedBrokerAndUserIDTest.class); - - protected String userName = "James"; - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory answer = super.createConnectionFactory(); - answer.setUserName(userName); - return answer; - } - - @Override - protected void configureBroker(BrokerService answer) throws Exception { - answer.setPopulateJMSXUserID(true); - super.configureBroker(answer); - } - - @Override - protected void assertMessagesReceivedAreValid(List receivedMessages) throws JMSException { - super.assertMessagesReceivedAreValid(receivedMessages); - - // lets assert that the user ID is set - for (Message message : receivedMessages) { - String userID = message.getStringProperty("JMSXUserID"); - LOG.info("Received message with userID: " + userID); - assertEquals("JMSXUserID header", userName, userID); - } - } - - protected void assertMessagesAreReceived2() throws JMSException { - waitForMessagesToBeDelivered(); - assertMessagesReceivedAreValid2(messages); - } - - protected void assertMessagesReceivedAreValid2(List receivedMessages) throws JMSException { - super.assertMessagesReceivedAreValid(receivedMessages); - - // lets assert that the user ID is set - for (Message message : receivedMessages) { - String userID = (String) message.getObjectProperty("JMSXUserID"); - LOG.info("Received message with userID: " + userID); - assertEquals("JMSXUserID header", userName, userID); - } - } - - public void testSpoofedJMSXUserIdIsIgnored() throws Exception { - Thread.sleep(1000); - messages.clear(); - - for (int i = 0; i < data.length; i++) { - Message message = createMessage(i); - configureMessage(message); - message.setStringProperty("JMSXUserID", "spoofedId"); - if (verbose) { - LOG.info("About to send a message: " + message + " with text: " + data[i]); - } - sendMessage(i, message); - } - assertMessagesAreReceived(); - LOG.info("" + data.length + " messages(s) received, closing down connections"); - } - - public void testSpoofedJMSXUserIdIsIgnoredAsObjectProperty() throws Exception { - Thread.sleep(1000); - messages.clear(); - - for (int i = 0; i < data.length; i++) { - Message message = createMessage(i); - configureMessage(message); - message.setStringProperty("JMSXUserID", "spoofedId"); - if (verbose) { - LOG.info("About to send a message: " + message + " with text: " + data[i]); - } - sendMessage(i, message); - } - assertMessagesAreReceived2(); - LOG.info("" + data.length + " messages(s) received, closing down connections"); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithTwoConnectionsAndByteSelectorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithTwoConnectionsAndByteSelectorTest.java deleted file mode 100644 index 208ef94330..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithTwoConnectionsAndByteSelectorTest.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.activemq.test; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; - -/** - * - */ -public class JmsTopicSendReceiveWithTwoConnectionsAndByteSelectorTest extends JmsTopicSendReceiveWithTwoConnectionsTest { - - @Override - protected void configureMessage(Message message) throws JMSException { - message.setByteProperty("dummy", (byte) 33); - } - - @Override - protected MessageConsumer createConsumer() throws JMSException { - return receiveSession.createConsumer(consumerDestination, "dummy = 33", false); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithTwoConnectionsAndEmbeddedBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithTwoConnectionsAndEmbeddedBrokerTest.java deleted file mode 100644 index fe7c7a5342..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/JmsTopicSendReceiveWithTwoConnectionsAndEmbeddedBrokerTest.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.activemq.test; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; - -/** - * - */ -public class JmsTopicSendReceiveWithTwoConnectionsAndEmbeddedBrokerTest extends JmsTopicSendReceiveWithTwoConnectionsTest { - - protected BrokerService broker; - protected String bindAddress = "tcp://localhost:61616"; - - /** - * Sets up a test where the producer and consumer have their own connection. - * - * @see junit.framework.TestCase#setUp() - */ - @Override - protected void setUp() throws Exception { - if (broker == null) { - broker = createBroker(); - } - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - - if (broker != null) { - broker.stop(); - } - } - - /** - * Factory method to create a new broker - * - * @throws Exception - */ - protected BrokerService createBroker() throws Exception { - BrokerService answer = new BrokerService(); - configureBroker(answer); - answer.start(); - return answer; - } - - protected void configureBroker(BrokerService answer) throws Exception { - answer.addConnector(bindAddress); - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(bindAddress); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/TemporaryDestinationToFromNameTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/TemporaryDestinationToFromNameTest.java deleted file mode 100644 index dc87782890..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/TemporaryDestinationToFromNameTest.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.activemq.test; - -import javax.jms.Queue; -import javax.jms.Session; -import javax.jms.Topic; - -import org.apache.activemq.EmbeddedBrokerAndConnectionTestSupport; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class TemporaryDestinationToFromNameTest extends EmbeddedBrokerAndConnectionTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(TemporaryDestinationToFromNameTest.class); - - public void testCreateTemporaryQueueThenCreateAQueueFromItsName() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - Queue tempQueue = session.createTemporaryQueue(); - String name = tempQueue.getQueueName(); - LOG.info("Created queue named: " + name); - - Queue createdQueue = session.createQueue(name); - - assertEquals("created queue not equal to temporary queue", tempQueue, createdQueue); - } - - public void testCreateTemporaryTopicThenCreateATopicFromItsName() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - Topic tempTopic = session.createTemporaryTopic(); - String name = tempTopic.getTopicName(); - LOG.info("Created topic named: " + name); - - Topic createdTopic = session.createTopic(name); - - assertEquals("created topic not equal to temporary topic", tempTopic, createdTopic); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/message/NestedMapAndListPropertyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/message/NestedMapAndListPropertyTest.java deleted file mode 100644 index c7d77f7269..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/message/NestedMapAndListPropertyTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.test.message; - -import javax.jms.JMSException; -import javax.jms.Message; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.activemq.test.JmsTopicSendReceiveWithTwoConnectionsAndEmbeddedBrokerTest; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Tests that a Message can have nested Map and List properties attached. - */ -public class NestedMapAndListPropertyTest extends JmsTopicSendReceiveWithTwoConnectionsAndEmbeddedBrokerTest { - - private static final Logger LOG = LoggerFactory.getLogger(NestedMapAndListPropertyTest.class); - - @Override - @SuppressWarnings("rawtypes") - protected void assertMessageValid(int index, Message message) throws JMSException { - Object value = message.getObjectProperty("textField"); - assertEquals("textField", data[index], value); - - Map map = (Map) message.getObjectProperty("mapField"); - assertNotNull(map); - assertEquals("mapField.a", "foo", map.get("a")); - assertEquals("mapField.b", Integer.valueOf(23), map.get("b")); - assertEquals("mapField.c", Long.valueOf(45), map.get("c")); - - value = map.get("d"); - assertTrue("mapField.d should be a Map", value instanceof Map); - map = (Map) value; - - assertEquals("mapField.d.x", "abc", map.get("x")); - value = map.get("y"); - assertTrue("mapField.d.y is a List", value instanceof List); - List list = (List) value; - LOG.debug("mapField.d.y: " + list); - assertEquals("listField.size", 3, list.size()); - - LOG.debug("Found map: " + map); - - list = (List) message.getObjectProperty("listField"); - LOG.debug("listField: " + list); - assertEquals("listField.size", 3, list.size()); - assertEquals("listField[0]", "a", list.get(0)); - assertEquals("listField[1]", "b", list.get(1)); - assertEquals("listField[2]", "c", list.get(2)); - assertEquals("JohnDoe", message.getStringProperty("JMSXUserID")); - } - - @Override - protected Message createMessage(int index) throws JMSException { - Message answer = session.createMessage(); - - answer.setStringProperty("textField", data[index]); - - Map grandChildMap = new HashMap<>(); - grandChildMap.put("x", "abc"); - grandChildMap.put("y", Arrays.asList(new Object[]{"a", "b", "c"})); - - Map nestedMap = new HashMap<>(); - nestedMap.put("a", "foo"); - nestedMap.put("b", Integer.valueOf(23)); - nestedMap.put("c", Long.valueOf(45)); - nestedMap.put("d", grandChildMap); - - answer.setObjectProperty("mapField", nestedMap); - answer.setObjectProperty("listField", Arrays.asList(new Object[]{"a", "b", "c"})); - answer.setStringProperty("JMSXUserID", "JohnDoe"); - - return answer; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/message/NestedMapMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/message/NestedMapMessageTest.java deleted file mode 100644 index 052ff17b1b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/message/NestedMapMessageTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.test.message; - -import javax.jms.JMSException; -import javax.jms.MapMessage; -import javax.jms.Message; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.activemq.test.JmsTopicSendReceiveWithTwoConnectionsAndEmbeddedBrokerTest; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class NestedMapMessageTest extends JmsTopicSendReceiveWithTwoConnectionsAndEmbeddedBrokerTest { - - private static final Logger LOG = LoggerFactory.getLogger(NestedMapMessageTest.class); - - @Override - @SuppressWarnings("rawtypes") - protected void assertMessageValid(int index, Message message) throws JMSException { - assertTrue("Should be a MapMessage: " + message, message instanceof MapMessage); - - MapMessage mapMessage = (MapMessage) message; - - Object value = mapMessage.getObject("textField"); - assertEquals("textField", data[index], value); - - Map map = (Map) mapMessage.getObject("mapField"); - assertNotNull(map); - assertEquals("mapField.a", "foo", map.get("a")); - assertEquals("mapField.b", Integer.valueOf(23), map.get("b")); - assertEquals("mapField.c", Long.valueOf(45), map.get("c")); - - value = map.get("d"); - assertTrue("mapField.d should be a Map", value instanceof Map); - map = (Map) value; - - assertEquals("mapField.d.x", "abc", map.get("x")); - value = map.get("y"); - assertTrue("mapField.d.y is a List", value instanceof List); - List list = (List) value; - LOG.debug("mapField.d.y: " + list); - assertEquals("listField.size", 3, list.size()); - - LOG.debug("Found map: " + map); - - list = (List) mapMessage.getObject("listField"); - LOG.debug("listField: " + list); - assertEquals("listField.size", 3, list.size()); - assertEquals("listField[0]", "a", list.get(0)); - assertEquals("listField[1]", "b", list.get(1)); - assertEquals("listField[2]", "c", list.get(2)); - } - - @Override - protected Message createMessage(int index) throws JMSException { - MapMessage answer = session.createMapMessage(); - - answer.setString("textField", data[index]); - - Map grandChildMap = new HashMap<>(); - grandChildMap.put("x", "abc"); - grandChildMap.put("y", Arrays.asList(new Object[]{"a", "b", "c"})); - - Map nestedMap = new HashMap<>(); - nestedMap.put("a", "foo"); - nestedMap.put("b", Integer.valueOf(23)); - nestedMap.put("c", Long.valueOf(45)); - nestedMap.put("d", grandChildMap); - - answer.setObject("mapField", nestedMap); - answer.setObject("listField", Arrays.asList(new Object[]{"a", "b", "c"})); - - return answer; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/DummyMessageQuery.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/DummyMessageQuery.java deleted file mode 100644 index 7136ac8890..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/DummyMessageQuery.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.test.retroactive; - -import javax.jms.MessageListener; - -import org.apache.activemq.broker.region.policy.MessageQuery; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQTextMessage; -import org.apache.activemq.command.Message; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * - */ -public class DummyMessageQuery implements MessageQuery { - - public static final int MESSAGE_COUNT = 10; - private static final Logger LOG = LoggerFactory.getLogger(DummyMessageQuery.class); - - @Override - public void execute(ActiveMQDestination destination, MessageListener listener) throws Exception { - LOG.info("Initial query is creating: " + MESSAGE_COUNT + " messages"); - for (int i = 0; i < MESSAGE_COUNT; i++) { - ActiveMQTextMessage message = new ActiveMQTextMessage(); - message.setText("Initial message: " + i + " loaded from query"); - listener.onMessage(message); - } - } - - @Override - public boolean validateUpdate(Message message) { - return true; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithDestinationBasedBufferTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithDestinationBasedBufferTest.java deleted file mode 100644 index 399177fdc4..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithDestinationBasedBufferTest.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.activemq.test.retroactive; - -/** - * - * - */ -public class RetroactiveConsumerTestWithDestinationBasedBufferTest extends RetroactiveConsumerTestWithSimpleMessageListTest { - - @Override - protected String getBrokerXml() { - return "org/apache/activemq/test/retroactive/activemq-fixed-destination-buffer.xml"; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithLastImagePolicyWithWildcardTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithLastImagePolicyWithWildcardTest.java deleted file mode 100644 index 5e78c6959e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithLastImagePolicyWithWildcardTest.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.activemq.test.retroactive; - -import javax.jms.JMSException; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.TextMessage; - -import org.apache.activemq.command.ActiveMQTopic; - -/** - * - */ -public class RetroactiveConsumerTestWithLastImagePolicyWithWildcardTest extends RetroactiveConsumerTestWithSimpleMessageListTest { - - private int counter = 1; - - @Override - protected void sendMessage(MessageProducer producer, TextMessage message) throws JMSException { - ActiveMQTopic topic = new ActiveMQTopic(destination.getPhysicalName() + "." + (counter++)); - producer.send(topic, message); - } - - @Override - protected MessageProducer createProducer() throws JMSException { - return session.createProducer(null); - } - - @Override - protected MessageConsumer createConsumer() throws JMSException { - return session.createConsumer(new ActiveMQTopic(destination.getPhysicalName() + ".>")); - } - - @Override - protected String getBrokerXml() { - return "org/apache/activemq/test/retroactive/activemq-lastimage-policy.xml"; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithSimpleMessageListTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithSimpleMessageListTest.java deleted file mode 100644 index ace29ef1d7..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithSimpleMessageListTest.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.activemq.test.retroactive; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.JMSException; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.net.URI; -import java.util.Date; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.util.MessageIdList; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class RetroactiveConsumerTestWithSimpleMessageListTest extends EmbeddedBrokerTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(RetroactiveConsumerTestWithSimpleMessageListTest.class); - - protected int messageCount = 20; - protected Connection connection; - protected Session session; - - public void testSendThenConsume() throws Exception { - - // lets some messages - connection = createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = createProducer(); - for (int i = 0; i < messageCount; i++) { - TextMessage message = session.createTextMessage("Message: " + i + " sent at: " + new Date()); - sendMessage(producer, message); - } - producer.close(); - session.close(); - connection.close(); - - connection = createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageConsumer consumer = createConsumer(); - MessageIdList listener = new MessageIdList(); - consumer.setMessageListener(listener); - listener.waitForMessagesToArrive(messageCount); - listener.assertMessagesReceived(messageCount); - - } - - @Override - protected void setUp() throws Exception { - useTopic = true; - bindAddress = "vm://localhost"; - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - if (session != null) { - session.close(); - session = null; - } - if (connection != null) { - connection.close(); - } - super.tearDown(); - } - - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory answer = new ActiveMQConnectionFactory(bindAddress); - answer.setUseRetroactiveConsumer(true); - return answer; - } - - @Override - protected BrokerService createBroker() throws Exception { - String uri = getBrokerXml(); - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } - - @Override - protected void startBroker() throws Exception { - // broker already started by XBean - } - - protected String getBrokerXml() { - return "org/apache/activemq/test/retroactive/activemq-fixed-buffer.xml"; - } - - protected MessageProducer createProducer() throws JMSException { - return session.createProducer(destination); - } - - protected void sendMessage(MessageProducer producer, TextMessage message) throws JMSException { - producer.send(message); - } - - protected MessageConsumer createConsumer() throws JMSException { - return session.createConsumer(destination); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithTimePolicyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithTimePolicyTest.java deleted file mode 100644 index b334d88ff3..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerTestWithTimePolicyTest.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.activemq.test.retroactive; - -/** - * - * - */ -public class RetroactiveConsumerTestWithTimePolicyTest extends RetroactiveConsumerTestWithSimpleMessageListTest { - - @Override - protected String getBrokerXml() { - return "org/apache/activemq/test/retroactive/activemq-timed-policy.xml"; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerWithMessageQueryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerWithMessageQueryTest.java deleted file mode 100644 index d91a1fd316..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/RetroactiveConsumerWithMessageQueryTest.java +++ /dev/null @@ -1,114 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.test.retroactive; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.net.URI; -import java.util.Date; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.util.MessageIdList; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class RetroactiveConsumerWithMessageQueryTest extends EmbeddedBrokerTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(RetroactiveConsumerWithMessageQueryTest.class); - - protected int messageCount = 20; - protected Connection connection; - protected Session session; - - public void testConsumeAndReceiveInitialQueryBeforeUpdates() throws Exception { - - // lets some messages - connection = createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - connection.start(); - - MessageConsumer consumer = session.createConsumer(destination); - MessageIdList listener = new MessageIdList(); - listener.setVerbose(true); - consumer.setMessageListener(listener); - - MessageProducer producer = session.createProducer(destination); - int updateMessageCount = messageCount - DummyMessageQuery.MESSAGE_COUNT; - for (int i = 0; i < updateMessageCount; i++) { - TextMessage message = session.createTextMessage("Update Message: " + i + " sent at: " + new Date()); - producer.send(message); - } - producer.close(); - LOG.info("Sent: " + updateMessageCount + " update messages"); - - listener.assertMessagesReceived(messageCount); - } - - @Override - protected void setUp() throws Exception { - useTopic = true; - bindAddress = "vm://localhost"; - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - if (session != null) { - session.close(); - session = null; - } - if (connection != null) { - connection.close(); - } - super.tearDown(); - } - - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory answer = new ActiveMQConnectionFactory(bindAddress); - // answer.setUseRetroactiveConsumer(true); - // option applied via destination policy alwaysRetroactive - return answer; - } - - @Override - protected BrokerService createBroker() throws Exception { - String uri = getBrokerXml(); - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } - - @Override - protected void startBroker() throws Exception { - // broker already started by XBean - } - - protected String getBrokerXml() { - return "org/apache/activemq/test/retroactive/activemq-message-query.xml"; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/activemq-fixed-buffer.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/activemq-fixed-buffer.xml deleted file mode 100644 index 820bdc0035..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/activemq-fixed-buffer.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/activemq-fixed-destination-buffer.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/activemq-fixed-destination-buffer.xml deleted file mode 100644 index 45d623c65f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/activemq-fixed-destination-buffer.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/activemq-lastimage-policy.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/activemq-lastimage-policy.xml deleted file mode 100644 index 0ee21a660b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/activemq-lastimage-policy.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/activemq-message-query.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/activemq-message-query.xml deleted file mode 100644 index 7b10860534..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/activemq-message-query.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/activemq-timed-policy.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/activemq-timed-policy.xml deleted file mode 100644 index 5e45fb3bc2..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/retroactive/activemq-timed-policy.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/CloseRollbackRedeliveryQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/CloseRollbackRedeliveryQueueTest.java deleted file mode 100644 index ca67d57858..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/CloseRollbackRedeliveryQueueTest.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.activemq.test.rollback; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.Session; -import javax.jms.TextMessage; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.jms.core.MessageCreator; - -public class CloseRollbackRedeliveryQueueTest extends EmbeddedBrokerTestSupport { - - private static final transient Logger LOG = LoggerFactory.getLogger(CloseRollbackRedeliveryQueueTest.class); - - protected int numberOfMessagesOnQueue = 1; - private Connection connection; - - public void testVerifySessionCloseRedeliveryWithFailoverTransport() throws Throwable { - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer consumer = session.createConsumer(destination); - - Message message = consumer.receive(1000); - String id = message.getJMSMessageID(); - assertNotNull(message); - LOG.info("got message " + message); - // close will rollback the current tx - session.close(); - - session = connection.createSession(true, Session.SESSION_TRANSACTED); - consumer = session.createConsumer(destination); - - message = consumer.receive(1000); - session.commit(); - assertNotNull(message); - assertEquals("redelivered message", id, message.getJMSMessageID()); - assertEquals(2, message.getLongProperty("JMSXDeliveryCount")); - } - - public void testVerifyConsumerAndSessionCloseRedeliveryWithFailoverTransport() throws Throwable { - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer consumer = session.createConsumer(destination); - - Message message = consumer.receive(1000); - String id = message.getJMSMessageID(); - assertNotNull(message); - LOG.info("got message " + message); - consumer.close(); - session.close(); - session = connection.createSession(true, Session.SESSION_TRANSACTED); - consumer = session.createConsumer(destination); - - message = consumer.receive(1000); - session.commit(); - assertNotNull(message); - assertEquals("redelivered message", id, message.getJMSMessageID()); - assertEquals(2, message.getLongProperty("JMSXDeliveryCount")); - } - - public void testVerifyConsumerCloseSessionRollbackRedeliveryWithFailoverTransport() throws Throwable { - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer consumer = session.createConsumer(destination); - - Message message = consumer.receive(1000); - String id = message.getJMSMessageID(); - assertNotNull(message); - LOG.info("got message " + message); - consumer.close(); - session.rollback(); - - consumer = session.createConsumer(destination); - message = consumer.receive(1000); - session.commit(); - assertNotNull(message); - assertEquals("redelivered message", id, message.getJMSMessageID()); - assertEquals(2, message.getLongProperty("JMSXDeliveryCount")); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - - connection = createConnection(); - connection.start(); - - // lets fill the queue up - for (int i = 0; i < numberOfMessagesOnQueue; i++) { - template.send(createMessageCreator(i)); - } - - } - - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - // failover: enables message audit - which could get in the way of redelivery - return new ActiveMQConnectionFactory("failover:" + bindAddress); - } - - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - super.tearDown(); - } - - protected MessageCreator createMessageCreator(final int i) { - return new MessageCreator() { - @Override - public Message createMessage(Session session) throws JMSException { - TextMessage answer = session.createTextMessage("Message: " + i); - answer.setIntProperty("Counter", i); - return answer; - } - }; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/DelegatingTransactionalMessageListener.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/DelegatingTransactionalMessageListener.java deleted file mode 100644 index bd1de387b8..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/DelegatingTransactionalMessageListener.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.activemq.test.rollback; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.Session; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DelegatingTransactionalMessageListener implements MessageListener { - - private static final transient Logger LOG = LoggerFactory.getLogger(DelegatingTransactionalMessageListener.class); - - private final MessageListener underlyingListener; - private boolean transacted = true; - private int ackMode = Session.AUTO_ACKNOWLEDGE; - private Session session; - - public DelegatingTransactionalMessageListener(MessageListener underlyingListener, - Connection connection, - Destination destination) { - this.underlyingListener = underlyingListener; - - try { - session = connection.createSession(transacted, ackMode); - MessageConsumer consumer = session.createConsumer(destination); - consumer.setMessageListener(this); - } catch (JMSException e) { - throw new IllegalStateException("Could not listen to " + destination, e); - } - } - - @Override - public void onMessage(Message message) { - try { - underlyingListener.onMessage(message); - session.commit(); - } catch (Throwable e) { - rollback(); - } - } - - private void rollback() { - try { - session.rollback(); - } catch (JMSException e) { - LOG.error("Failed to rollback: " + e, e); - } - } - - public Session getSession() { - return session; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/RollbacksWhileConsumingLargeQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/RollbacksWhileConsumingLargeQueueTest.java deleted file mode 100644 index e648fd743b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/test/rollback/RollbacksWhileConsumingLargeQueueTest.java +++ /dev/null @@ -1,186 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.test.rollback; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.RedeliveryPolicy; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.jms.core.MessageCreator; - -/** - * - */ -public class RollbacksWhileConsumingLargeQueueTest extends EmbeddedBrokerTestSupport implements MessageListener { - - private static final transient Logger LOG = LoggerFactory.getLogger(RollbacksWhileConsumingLargeQueueTest.class); - - protected int numberOfMessagesOnQueue = 650; - private Connection connection; - private AtomicInteger deliveryCounter = new AtomicInteger(0); - private AtomicInteger ackCounter = new AtomicInteger(0); - private CountDownLatch latch; - private Throwable failure; - - public void testWithReciever() throws Throwable { - latch = new CountDownLatch(numberOfMessagesOnQueue); - Session session = connection.createSession(true, 0); - MessageConsumer consumer = session.createConsumer(destination); - - long start = System.currentTimeMillis(); - while ((System.currentTimeMillis() - start) < 1000 * 1000) { - if (getFailure() != null) { - throw getFailure(); - } - - // Are we done receiving all the messages. - if (ackCounter.get() == numberOfMessagesOnQueue) { - return; - } - - Message message = consumer.receive(1000); - if (message == null) { - continue; - } - - try { - onMessage(message); - session.commit(); - } catch (Throwable e) { - session.rollback(); - } - } - - fail("Did not receive all the messages."); - } - - public void testWithMessageListener() throws Throwable { - latch = new CountDownLatch(numberOfMessagesOnQueue); - new DelegatingTransactionalMessageListener(this, connection, destination); - - long start = System.currentTimeMillis(); - while ((System.currentTimeMillis() - start) < 1000 * 1000) { - - if (getFailure() != null) { - throw getFailure(); - } - - if (latch.await(1, TimeUnit.SECONDS)) { - LOG.debug("Received: " + deliveryCounter.get() + " message(s)"); - return; - } - - } - - fail("Did not receive all the messages."); - } - - @Override - protected ConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory answer = (ActiveMQConnectionFactory) super.createConnectionFactory(); - RedeliveryPolicy policy = new RedeliveryPolicy(); - policy.setMaximumRedeliveries(3); - policy.setRedeliveryDelay(0); - policy.setInitialRedeliveryDelay(0); - policy.setUseExponentialBackOff(false); - answer.setRedeliveryPolicy(policy); - return answer; - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - - connection = createConnection(); - connection.start(); - - // lets fill the queue up - for (int i = 0; i < numberOfMessagesOnQueue; i++) { - template.send(createMessageCreator(i)); - } - - } - - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - super.tearDown(); - } - - protected MessageCreator createMessageCreator(final int i) { - return new MessageCreator() { - @Override - public Message createMessage(Session session) throws JMSException { - TextMessage answer = session.createTextMessage("Message: " + i); - answer.setIntProperty("Counter", i); - return answer; - } - }; - } - - @Override - public void onMessage(Message message) { - String msgId = null; - String msgText = null; - - try { - msgId = message.getJMSMessageID(); - msgText = ((TextMessage) message).getText(); - } catch (JMSException e) { - setFailure(e); - } - - try { - assertEquals("Message: " + ackCounter.get(), msgText); - } catch (Throwable e) { - setFailure(e); - } - - int value = deliveryCounter.incrementAndGet(); - if (value % 2 == 0) { - LOG.info("Rolling Back message: " + ackCounter.get() + " id: " + msgId + ", content: " + msgText); - throw new RuntimeException("Dummy exception on message: " + value); - } - - LOG.info("Received message: " + ackCounter.get() + " id: " + msgId + ", content: " + msgText); - ackCounter.incrementAndGet(); - latch.countDown(); - } - - public synchronized Throwable getFailure() { - return failure; - } - - public synchronized void setFailure(Throwable failure) { - this.failure = failure; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryNetworkReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryNetworkReconnectTest.java deleted file mode 100644 index d36ae118ea..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryNetworkReconnectTest.java +++ /dev/null @@ -1,222 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.transport.discovery; - -import javax.management.ObjectInstance; -import javax.management.ObjectName; -import java.net.URI; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.jmx.ManagementContext; -import org.apache.activemq.util.SocketProxy; -import org.apache.activemq.util.Wait; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.jmock.Expectations; -import org.jmock.Mockery; -import org.jmock.api.Invocation; -import org.jmock.integration.junit4.JMock; -import org.jmock.integration.junit4.JUnit4Mockery; -import org.jmock.lib.action.CustomAction; -import org.jmock.lib.legacy.ClassImposteriser; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertTrue; - -@RunWith(JMock.class) -public class DiscoveryNetworkReconnectTest { - - private static final Logger LOG = LoggerFactory.getLogger(DiscoveryNetworkReconnectTest.class); - final int maxReconnects = 2; - final String groupName = "GroupID-" + "DiscoveryNetworkReconnectTest"; - final String discoveryAddress = "multicast://default?group=" + groupName + "&initialReconnectDelay=1000"; - final Semaphore mbeanRegistered = new Semaphore(0); - final Semaphore mbeanUnregistered = new Semaphore(0); - BrokerService brokerA, brokerB; - Mockery context; - ManagementContext managementContext; - DiscoveryAgent agent; - SocketProxy proxy; - - // ignore the hostname resolution component as this is machine dependent - class NetworkBridgeObjectNameMatcher extends BaseMatcher { - - T name; - - NetworkBridgeObjectNameMatcher(T o) { - name = o; - } - - @Override - public boolean matches(Object arg0) { - ObjectName other = (ObjectName) arg0; - ObjectName mine = (ObjectName) name; - LOG.info("Match: " + mine + " vs: " + other); - - if (!"networkConnectors".equals(other.getKeyProperty("connector"))) { - return false; - } - return other.getKeyProperty("connector").equals(mine.getKeyProperty("connector")) && - other.getKeyProperty("networkBridge") != null && mine.getKeyProperty("networkBridge") != null; - } - - @Override - public void describeTo(Description arg0) { - arg0.appendText(this.getClass().getName()); - } - } - - @Before - public void setUp() throws Exception { - context = new JUnit4Mockery() {{ - setImposteriser(ClassImposteriser.INSTANCE); - }}; - brokerA = new BrokerService(); - brokerA.setBrokerName("BrokerA"); - configure(brokerA); - brokerA.addConnector("tcp://localhost:0"); - brokerA.start(); - brokerA.waitUntilStarted(); - - proxy = new SocketProxy(brokerA.getTransportConnectors().get(0).getConnectUri()); - managementContext = context.mock(ManagementContext.class); - - context.checking(new Expectations() {{ - allowing(managementContext).getJmxDomainName(); - will(returnValue("Test")); - allowing(managementContext).setBrokerName("BrokerNC"); - allowing(managementContext).start(); - allowing(managementContext).isCreateConnector(); - allowing(managementContext).stop(); - allowing(managementContext).isConnectorStarted(); - - // expected MBeans - allowing(managementContext).registerMBean(with(any(Object.class)), with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC")))); - allowing(managementContext).registerMBean(with(any(Object.class)), with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,service=Health")))); - allowing(managementContext).registerMBean(with(any(Object.class)), with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,connector=networkConnectors,networkConnectorName=NC")))); - allowing(managementContext).registerMBean(with(any(Object.class)), with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,service=Log4JConfiguration")))); - allowing(managementContext).registerMBean(with(any(Object.class)), with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,destinationType=Topic,destinationName=ActiveMQ.Advisory.Connection")))); - allowing(managementContext).registerMBean(with(any(Object.class)), with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,destinationType=Topic,destinationName=ActiveMQ.Advisory.NetworkBridge")))); - allowing(managementContext).registerMBean(with(any(Object.class)), with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,destinationType=Topic,destinationName=ActiveMQ.Advisory.MasterBroker")))); - allowing(managementContext).registerMBean(with(any(Object.class)), with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,service=jobScheduler,jobSchedulerName=JMS")))); - - atLeast(maxReconnects - 1).of(managementContext).registerMBean(with(any(Object.class)), with(new NetworkBridgeObjectNameMatcher<>(new ObjectName("Test:type=Broker,brokerName=BrokerNC,connector=networkConnectors,networkConnectorName=NC,networkBridge=localhost/127.0.0.1_" + proxy.getUrl().getPort())))); - will(new CustomAction("signal register network mbean") { - @Override - public Object invoke(Invocation invocation) throws Throwable { - LOG.info("Mbean Registered: " + invocation.getParameter(0)); - mbeanRegistered.release(); - return new ObjectInstance((ObjectName) invocation.getParameter(1), "discription"); - } - }); - atLeast(maxReconnects - 1).of(managementContext).unregisterMBean(with(new NetworkBridgeObjectNameMatcher<>(new ObjectName("Test:type=Broker,brokerName=BrokerNC,connector=networkConnectors,networkConnectorName=NC,networkBridge=localhost/127.0.0.1_" + proxy.getUrl().getPort())))); - will(new CustomAction("signal unregister network mbean") { - @Override - public Object invoke(Invocation invocation) throws Throwable { - LOG.info("Mbean Unregistered: " + invocation.getParameter(0)); - mbeanUnregistered.release(); - return null; - } - }); - - allowing(managementContext).unregisterMBean(with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC")))); - allowing(managementContext).unregisterMBean(with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,service=Health")))); - allowing(managementContext).unregisterMBean(with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,connector=networkConnectors,networkConnectorName=NC")))); - allowing(managementContext).unregisterMBean(with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,service=Log4JConfiguration")))); - allowing(managementContext).unregisterMBean(with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,destinationType=Topic,destinationName=ActiveMQ.Advisory.Connection")))); - allowing(managementContext).unregisterMBean(with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,destinationType=Topic,destinationName=ActiveMQ.Advisory.NetworkBridge")))); - allowing(managementContext).unregisterMBean(with(equal(new ObjectName("Test:type=Broker,brokerName=BrokerNC,destinationType=Topic,destinationName=ActiveMQ.Advisory.MasterBroker")))); - }}); - - brokerB = new BrokerService(); - brokerB.setManagementContext(managementContext); - brokerB.setBrokerName("BrokerNC"); - configure(brokerB); - } - - @After - public void tearDown() throws Exception { - brokerA.stop(); - brokerA.waitUntilStopped(); - brokerB.stop(); - brokerB.waitUntilStopped(); - proxy.close(); - } - - private void configure(BrokerService broker) { - broker.setPersistent(false); - broker.setUseJmx(true); - } - - @Test - public void testMulicastReconnect() throws Exception { - - brokerB.addNetworkConnector(discoveryAddress + "&discovered.trace=true&discovered.wireFormat.maxInactivityDuration=1000&discovered.wireFormat.maxInactivityDurationInitalDelay=1000"); - brokerB.start(); - brokerB.waitUntilStarted(); - - // control multicast advertise agent to inject proxy - agent = DiscoveryAgentFactory.createDiscoveryAgent(new URI(discoveryAddress)); - agent.registerService(proxy.getUrl().toString()); - agent.start(); - - doReconnect(); - } - - @Test - public void testSimpleReconnect() throws Exception { - brokerB.addNetworkConnector("simple://(" + proxy.getUrl() + ")?useExponentialBackOff=false&initialReconnectDelay=500&discovered.wireFormat.maxInactivityDuration=1000&discovered.wireFormat.maxInactivityDurationInitalDelay=1000"); - brokerB.start(); - brokerB.waitUntilStarted(); - doReconnect(); - } - - private void doReconnect() throws Exception { - - for (int i = 0; i < maxReconnects; i++) { - // Wait for connection - assertTrue("we got a network connection in a timely manner", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return proxy.connections.size() >= 1; - } - })); - - // wait for network connector - assertTrue("network connector mbean registered within 1 minute", mbeanRegistered.tryAcquire(60, TimeUnit.SECONDS)); - - // force an inactivity timeout via the proxy - proxy.pause(); - - // wait for the inactivity timeout and network shutdown - assertTrue("network connector mbean unregistered within 1 minute", mbeanUnregistered.tryAcquire(60, TimeUnit.SECONDS)); - - // whack all connections - proxy.close(); - - // let a reconnect succeed - proxy.reopen(); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryTransportBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryTransportBrokerTest.java deleted file mode 100644 index f6373aa34d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryTransportBrokerTest.java +++ /dev/null @@ -1,166 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.transport.discovery; - -import javax.jms.DeliveryMode; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; - -import junit.framework.Test; - -import org.apache.activemq.broker.StubConnection; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ConnectionInfo; -import org.apache.activemq.command.ConsumerInfo; -import org.apache.activemq.command.ProducerInfo; -import org.apache.activemq.command.SessionInfo; -import org.apache.activemq.network.NetworkTestSupport; -import org.apache.activemq.transport.Transport; -import org.apache.activemq.transport.TransportFactory; -import org.apache.activemq.transport.failover.FailoverTransport; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DiscoveryTransportBrokerTest extends NetworkTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(DiscoveryTransportBrokerTest.class); - - String groupName; - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - } - - public void testPublisherFailsOver() throws Exception { - ActiveMQDestination destination = new ActiveMQQueue("TEST"); - int deliveryMode = DeliveryMode.NON_PERSISTENT; - - // Start a normal consumer on the local broker - StubConnection connection1 = createConnection(); - ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); - ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, destination); - connection1.send(connectionInfo1); - connection1.send(sessionInfo1); - connection1.request(consumerInfo1); - - // Start a normal consumer on a remote broker - StubConnection connection2 = createRemoteConnection(); - ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); - connection2.send(connectionInfo2); - connection2.send(sessionInfo2); - connection2.request(consumerInfo2); - - // Start a failover publisher. - StubConnection connection3 = createFailoverConnection(); - ConnectionInfo connectionInfo3 = createConnectionInfo(); - SessionInfo sessionInfo3 = createSessionInfo(connectionInfo3); - ProducerInfo producerInfo3 = createProducerInfo(sessionInfo3); - connection3.send(connectionInfo3); - connection3.send(sessionInfo3); - connection3.send(producerInfo3); - - // Send the message using the fail over publisher. - connection3.request(createMessage(producerInfo3, destination, deliveryMode)); - - // The message will be sent to one of the brokers. - FailoverTransport ft = connection3.getTransport().narrow(FailoverTransport.class); - - // See which broker we were connected to. - StubConnection connectionA; - StubConnection connectionB; - TransportConnector serverA; - if (connector.getServer().getConnectURI().getPort() == ft.getConnectedTransportURI().getPort()) { - connectionA = connection1; - connectionB = connection2; - serverA = connector; - } else { - connectionA = connection2; - connectionB = connection1; - serverA = remoteConnector; - } - - assertNotNull(receiveMessage(connectionA)); - assertNoMessagesLeft(connectionB); - - // Dispose the server so that it fails over to the other server. - LOG.info("Disconnecting active server"); - serverA.stop(); - - LOG.info("Sending request that should failover"); - connection3.request(createMessage(producerInfo3, destination, deliveryMode)); - - assertNotNull(receiveMessage(connectionB)); - assertNoMessagesLeft(connectionA); - - } - - @Override - protected String getLocalURI() { - return "tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true"; - } - - @Override - protected String getRemoteURI() { - return "tcp://localhost:0?wireFormat.tcpNoDelayEnabled=true"; - } - - @Override - protected TransportConnector createConnector() throws Exception, IOException, URISyntaxException { - TransportConnector x = super.createConnector(); - x.setDiscoveryUri(new URI(getDiscoveryUri())); - return x; - } - - protected String getDiscoveryUri() { - if (groupName == null) { - groupName = "group-" + System.currentTimeMillis(); - } - return "multicast://default?group=" + groupName; - } - - @Override - protected TransportConnector createRemoteConnector() throws Exception, IOException, URISyntaxException { - TransportConnector x = super.createRemoteConnector(); - x.setDiscoveryUri(new URI(getDiscoveryUri())); - return x; - } - - protected StubConnection createFailoverConnection() throws Exception { - URI failoverURI = new URI("discovery:(" + getDiscoveryUri() + ")?startupMaxReconnectAttempts=10&initialReconnectDelay=1000"); - Transport transport = TransportFactory.connect(failoverURI); - StubConnection connection = new StubConnection(transport); - connections.add(connection); - return connection; - } - - public static Test suite() { - return suite(DiscoveryTransportBrokerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryTransportNoBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryTransportNoBrokerTest.java deleted file mode 100644 index a529e6c610..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryTransportNoBrokerTest.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.activemq.transport.discovery; - -import javax.jms.Connection; -import javax.jms.JMSException; -import java.net.URI; -import java.util.Map; -import java.util.Vector; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.CombinationTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.command.DiscoveryEvent; -import org.apache.activemq.transport.StubCompositeTransport; -import org.apache.activemq.util.URISupport; -import org.apache.activemq.util.URISupport.CompositeData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DiscoveryTransportNoBrokerTest extends CombinationTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(DiscoveryTransportNoBrokerTest.class); - - @Override - public void setUp() throws Exception { - setAutoFail(true); - super.setUp(); - } - - public void testNoExtraThreads() throws Exception { - BrokerService broker = new BrokerService(); - TransportConnector tcp = broker.addConnector("tcp://localhost:0?transport.closeAsync=false"); - String group = "GR-" + System.currentTimeMillis(); - URI discoveryUri = new URI("multicast://default?group=" + group); - tcp.setDiscoveryUri(discoveryUri); - broker.start(); - broker.waitUntilStarted(); - - Vector existingNames = new Vector<>(); - Thread[] threads = getThreads(); - for (Thread t : threads) { - existingNames.add(t.getName()); - } - final int idleThreadCount = threads.length; - LOG.info("Broker started - thread Count:" + idleThreadCount); - - final int noConnectionToCreate = 10; - for (int i = 0; i < 10; i++) { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("discovery:(multicast://239.255.2.3:6155?group=" + group + ")?closeAsync=false&startupMaxReconnectAttempts=10&initialReconnectDelay=1000"); - LOG.info("Connecting."); - Connection connection = factory.createConnection(); - connection.setClientID("test"); - connection.close(); - } - Thread.sleep(2000); - threads = getThreads(); - for (Thread t : threads) { - if (!existingNames.contains(t.getName())) { - LOG.info("Remaining thread:" + t); - } - } - assertTrue("no extra threads per connection", Thread.activeCount() - idleThreadCount < noConnectionToCreate); - } - - private Thread[] getThreads() { - Thread[] threads = new Thread[Thread.activeCount()]; - Thread.enumerate(threads); - return threads; - } - - public void testMaxReconnectAttempts() throws JMSException { - try { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("discovery:(multicast://doesNOTexist)"); - LOG.info("Connecting."); - Connection connection = factory.createConnection(); - connection.setClientID("test"); - fail("Did not fail to connect as expected."); - } catch (JMSException expected) { - assertTrue("reason is java.io.IOException, was: " + expected.getCause(), expected.getCause() instanceof java.io.IOException); - } - } - - public void testInitialConnectDelayWithNoBroker() throws Exception { - // the initialReconnectDelay only kicks in once a set of connect URL have - // been returned from the discovery agent. - // Up to that point the reconnectDelay is used which has a default value of 10 - // - long initialReconnectDelay = 4000; - long startT = System.currentTimeMillis(); - String groupId = "WillNotMatch" + startT; - try { - String urlStr = "discovery:(multicast://default?group=" + groupId + - ")?useExponentialBackOff=false&maxReconnectAttempts=2&reconnectDelay=" + initialReconnectDelay; - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(urlStr); - LOG.info("Connecting."); - Connection connection = factory.createConnection(); - connection.setClientID("test"); - fail("Did not fail to connect as expected."); - } catch (JMSException expected) { - assertTrue("reason is java.io.IOException, was: " + expected.getCause(), expected.getCause() instanceof java.io.IOException); - long duration = System.currentTimeMillis() - startT; - assertTrue("took at least initialReconnectDelay time: " + duration + " e:" + expected, duration >= initialReconnectDelay); - } - } - - public void testSetDiscoveredBrokerProperties() throws Exception { - final String extraParameterName = "connectionTimeout"; - final String extraParameterValue = "3000"; - final URI uri = new URI("discovery:(multicast://default)?initialReconnectDelay=100&" + DiscoveryListener.DISCOVERED_OPTION_PREFIX + extraParameterName + "=" + extraParameterValue); - CompositeData compositeData = URISupport.parseComposite(uri); - - StubCompositeTransport compositeTransport = new StubCompositeTransport(); - DiscoveryTransport discoveryTransport = DiscoveryTransportFactory.createTransport(compositeTransport, compositeData, compositeData.getParameters()); - - discoveryTransport.onServiceAdd(new DiscoveryEvent("tcp://localhost:61616")); - assertEquals("expected added URI after discovery event", compositeTransport.getTransportURIs().length, 1); - - URI discoveredServiceURI = compositeTransport.getTransportURIs()[0]; - Map parameters = URISupport.parseParameters(discoveredServiceURI); - assertTrue("unable to add parameter to discovered service", parameters.containsKey(extraParameterName)); - assertEquals("incorrect value for parameter added to discovered service", parameters.get(extraParameterName), extraParameterValue); - } - - public void testSetDiscoveredStaticBrokerProperties() throws Exception { - final String extraParameterName = "connectionTimeout"; - final String extraParameterValue = "3000"; - final URI uri = new URI("discovery:(static:tcp://localhost:61616)?initialReconnectDelay=100&" + DiscoveryListener.DISCOVERED_OPTION_PREFIX + extraParameterName + "=" + extraParameterValue); - CompositeData compositeData = URISupport.parseComposite(uri); - - StubCompositeTransport compositeTransport = new StubCompositeTransport(); - DiscoveryTransport discoveryTransport = DiscoveryTransportFactory.createTransport(compositeTransport, compositeData, compositeData.getParameters()); - - discoveryTransport.start(); - assertEquals("expected added URI after discovery event", 1, compositeTransport.getTransportURIs().length); - - URI discoveredServiceURI = compositeTransport.getTransportURIs()[0]; - Map parameters = URISupport.parseParameters(discoveredServiceURI); - assertTrue("unable to add parameter to discovered service", parameters.containsKey(extraParameterName)); - assertEquals("incorrect value for parameter added to discovered service", parameters.get(extraParameterName), extraParameterValue); - } - - public void testAddRemoveDiscoveredBroker() throws Exception { - final URI uri = new URI("discovery:(multicast://default)?initialReconnectDelay=100&connectionTimeout=3000"); - CompositeData compositeData = URISupport.parseComposite(uri); - - StubCompositeTransport compositeTransport = new StubCompositeTransport(); - DiscoveryTransport discoveryTransport = DiscoveryTransportFactory.createTransport(compositeTransport, compositeData, compositeData.getParameters()); - - final String serviceName = "tcp://localhost:61616"; - discoveryTransport.onServiceAdd(new DiscoveryEvent(serviceName)); - assertEquals("expected added URI after discovery event", 1, compositeTransport.getTransportURIs().length); - - discoveryTransport.onServiceRemove(new DiscoveryEvent(serviceName)); - assertEquals("expected URI removed after discovery event", 0, compositeTransport.getTransportURIs().length); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryUriTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryUriTest.java deleted file mode 100644 index 20434d3d3e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/DiscoveryUriTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.transport.discovery; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.net.URI; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; - -public class DiscoveryUriTest extends EmbeddedBrokerTestSupport { - - @Override - protected BrokerService createBroker() throws Exception { - bindAddress = "tcp://localhost:0"; - BrokerService answer = new BrokerService(); - answer.setPersistent(isPersistent()); - TransportConnector connector = new TransportConnector(); - connector.setUri(new URI(bindAddress)); - connector.setDiscoveryUri(new URI("multicast://default?group=test")); - answer.addConnector(connector); - return answer; - } - - public void testConnect() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("discovery:(multicast://default?group=test)?reconnectDelay=1000&maxReconnectAttempts=30&useExponentialBackOff=false"); - Connection conn = factory.createConnection(); - conn.start(); - - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = sess.createProducer(sess.createQueue("test")); - producer.send(sess.createTextMessage("test")); - MessageConsumer consumer = sess.createConsumer(sess.createQueue("test")); - Message msg = consumer.receive(1000); - assertNotNull(msg); - } - - public void testFailedConnect() throws Exception { - try { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("discovery:(multicast://default?group=test1)?reconnectDelay=1000&startupMaxReconnectAttempts=3&useExponentialBackOff=false"); - Connection conn = factory.createConnection(); - conn.start(); - } catch (Exception e) { - return; - } - fail("Expected connection failure"); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/ZeroconfDiscoverTransportTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/ZeroconfDiscoverTransportTest.java deleted file mode 100644 index 598a3014d2..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/discovery/ZeroconfDiscoverTransportTest.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.activemq.transport.discovery; - -/** - * - * - */ -public class ZeroconfDiscoverTransportTest extends DiscoveryTransportBrokerTest { - - @Override - protected String getDiscoveryUri() { - return "zeroconf://cheese"; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/CompositeMessageCursorUsageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/CompositeMessageCursorUsageTest.java deleted file mode 100644 index 52c2cc2111..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/CompositeMessageCursorUsageTest.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.activemq.usage; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.management.ObjectName; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.jmx.QueueViewMBean; -import org.springframework.jms.core.JmsTemplate; -import org.springframework.jms.core.MessageCreator; - -public class CompositeMessageCursorUsageTest extends TestCase { - - BrokerService broker; - - @Override - public void setUp() throws Exception { - broker = new BrokerService(); - broker.setPersistent(false); - broker.start(); - } - - @Override - protected void tearDown() throws Exception { - broker.stop(); - } - - public void testCompositeMessageUsage() throws Exception { - - String compositeQueue = "compositeA,compositeB"; - - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost"); - JmsTemplate jt = new JmsTemplate(cf); - - jt.send(compositeQueue, new MessageCreator() { - @Override - public Message createMessage(Session session) throws JMSException { - TextMessage tm = session.createTextMessage(); - tm.setText("test"); - return tm; - } - }); - - jt.send("noCompositeA", new MessageCreator() { - @Override - public Message createMessage(Session session) throws JMSException { - TextMessage tm = session.createTextMessage(); - tm.setText("test"); - return tm; - } - }); - - jt.send("noCompositeB", new MessageCreator() { - @Override - public Message createMessage(Session session) throws JMSException { - TextMessage tm = session.createTextMessage(); - tm.setText("test"); - return tm; - } - }); - - assertEquals("Cursor memory usage wrong for 'noCompositeA' queue", 1032, getQueueView("noCompositeA").getCursorMemoryUsage()); - assertEquals("Cursor memory usage wrong for 'noCompositeB' queue", 1032, getQueueView("noCompositeB").getCursorMemoryUsage()); - assertEquals("Cursor memory usage wrong for 'CompositeA' queue", 1032, getQueueView("compositeA").getCursorMemoryUsage()); - assertEquals("Cursor memory usage wrong for 'CompositeB' queue", 1032, getQueueView("compositeB").getCursorMemoryUsage()); - - } - - public QueueViewMBean getQueueView(String queueName) throws Exception { - ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq" + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + queueName); - return (QueueViewMBean) broker.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/JobSchedulerStoreUsageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/JobSchedulerStoreUsageTest.java deleted file mode 100644 index c23c4e2b34..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/JobSchedulerStoreUsageTest.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.activemq.usage; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.Message; -import javax.jms.Session; -import java.io.File; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.ScheduledMessage; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.util.IOHelper; -import org.apache.activemq.util.ProducerThread; -import org.apache.activemq.util.Wait; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class JobSchedulerStoreUsageTest extends EmbeddedBrokerTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(JobSchedulerStoreUsageTest.class); - - final int WAIT_TIME_MILLS = 20 * 1000; - - @Override - protected BrokerService createBroker() throws Exception { - File schedulerDirectory = new File("target/scheduler"); - - IOHelper.mkdirs(schedulerDirectory); - IOHelper.deleteChildren(schedulerDirectory); - - BrokerService broker = super.createBroker(); - broker.setSchedulerSupport(true); - broker.setSchedulerDirectoryFile(schedulerDirectory); - broker.getSystemUsage().getJobSchedulerUsage().setLimit(7 * 1024); - broker.deleteAllMessages(); - return broker; - } - - @Override - protected boolean isPersistent() { - return true; - } - - public void testJmx() throws Exception { - - LOG.info("Initial scheduler usage: {}", broker.getAdminView().getJobSchedulerStorePercentUsage()); - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection conn = factory.createConnection(); - conn.start(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination dest = sess.createQueue(this.getClass().getName()); - final ProducerThread producer = new ProducerThread(sess, dest) { - @Override - protected Message createMessage(int i) throws Exception { - Message message = super.createMessage(i); - message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, WAIT_TIME_MILLS / 2); - return message; - } - }; - producer.setMessageCount(100); - producer.start(); - - assertEquals(7 * 1024, broker.getAdminView().getJobSchedulerStoreLimit()); - - // wait for the producer to block - Thread.sleep(WAIT_TIME_MILLS / 2); - - assertTrue(broker.getAdminView().getJobSchedulerStorePercentUsage() > 100); - - broker.getAdminView().setJobSchedulerStoreLimit(1024 * 1024 * 33); - - Thread.sleep(WAIT_TIME_MILLS); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return producer.getSentCount() == producer.getMessageCount(); - } - }, WAIT_TIME_MILLS * 2); - - assertEquals("Producer didn't send all messages", producer.getMessageCount(), producer.getSentCount()); - - LOG.info("Final scheduler usage: {}", broker.getAdminView().getJobSchedulerStorePercentUsage()); - - assertTrue(broker.getAdminView().getJobSchedulerStorePercentUsage() < 100); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/StoreUsageLimitsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/StoreUsageLimitsTest.java deleted file mode 100644 index 38f5598128..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/StoreUsageLimitsTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.usage; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; - -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.broker.BrokerService; - -public class StoreUsageLimitsTest extends EmbeddedBrokerTestSupport { - - final int WAIT_TIME_MILLS = 20 * 1000; - private static final String limitsLogLevel = "warn"; - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - broker.getSystemUsage().getMemoryUsage().setLimit(Long.MAX_VALUE); - broker.getSystemUsage().setCheckLimitsLogLevel(limitsLogLevel); - broker.deleteAllMessages(); - return broker; - } - - @Override - protected boolean isPersistent() { - return true; - } - - public void testCheckLimitsLogLevel() throws Exception { - - File file = new File("target/activemq-test.log"); - if (!file.exists()) { - fail("target/activemq-test.log was not created."); - } - - BufferedReader br = null; - boolean foundUsage = false; - - try { - br = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); - String line = null; - while ((line = br.readLine()) != null) { - if (line.contains(new String(Long.toString(Long.MAX_VALUE / (1024 * 1024)))) && line.contains(limitsLogLevel.toUpperCase())) { - foundUsage = true; - } - } - } catch (Exception e) { - fail(e.getMessage()); - } finally { - br.close(); - } - - if (!foundUsage) - fail("checkLimitsLogLevel message did not write to log target/activemq-test.log"); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/StoreUsageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/StoreUsageTest.java deleted file mode 100644 index 6f4fe82acc..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usage/StoreUsageTest.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.activemq.usage; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.Session; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.util.ProducerThread; -import org.apache.activemq.util.Wait; - -public class StoreUsageTest extends EmbeddedBrokerTestSupport { - - final int WAIT_TIME_MILLS = 20 * 1000; - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService broker = super.createBroker(); - broker.getSystemUsage().getStoreUsage().setLimit(10 * 1024); - broker.deleteAllMessages(); - return broker; - } - - @Override - protected boolean isPersistent() { - return true; - } - - public void testJmx() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection conn = factory.createConnection(); - conn.start(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination dest = sess.createQueue(this.getClass().getName()); - final ProducerThread producer = new ProducerThread(sess, dest); - producer.start(); - - // wait for the producer to block - Thread.sleep(WAIT_TIME_MILLS / 2); - - broker.getAdminView().setStoreLimit(1024 * 1024); - - Thread.sleep(WAIT_TIME_MILLS); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return producer.getSentCount() == producer.getMessageCount(); - } - }, WAIT_TIME_MILLS * 2); - - assertEquals("Producer didn't send all messages", producer.getMessageCount(), producer.getSentCount()); - - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AMQ2927Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AMQ2927Test.java deleted file mode 100644 index 49ae667017..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AMQ2927Test.java +++ /dev/null @@ -1,132 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.MessageConsumer; -import java.net.URI; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.util.MessageIdList; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class AMQ2927Test extends JmsMultipleBrokersTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(AMQ2927Test.class); - - ActiveMQQueue queue = new ActiveMQQueue("TEST"); - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - BrokerService brokerA = createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=true&useJmx=false&deleteAllMessagesOnStartup=true")); - brokerA.setBrokerId("BrokerA"); - BrokerService brokerB = createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=true&useJmx=false&deleteAllMessagesOnStartup=true")); - brokerB.setBrokerId("BrokerB"); - NetworkConnector aTOb = bridgeBrokers(brokers.get("BrokerA").broker, brokers.get("BrokerB").broker, false, 2, true, true); - aTOb.addStaticallyIncludedDestination(queue); - NetworkConnector bTOa = bridgeBrokers(brokers.get("BrokerB").broker, brokers.get("BrokerA").broker, false, 2, true, true); - bTOa.addStaticallyIncludedDestination(queue); - - startAllBrokers(); - waitForBridgeFormation(); - - } - - public void testRestartSend() throws Exception { - - Thread.sleep(1000); - - LOG.info("restarting broker"); - - restartBroker("BrokerA"); - - Thread.sleep(5000); - - LOG.info("sending message"); - - sendMessages("BrokerA", queue, 1); - - Thread.sleep(3000); - - LOG.info("consuming message"); - - MessageConsumer consumerA = createConsumer("BrokerA", queue); - MessageConsumer consumerB = createConsumer("BrokerB", queue); - - Thread.sleep(1000); - - MessageIdList messagesA = getConsumerMessages("BrokerA", consumerA); - MessageIdList messagesB = getConsumerMessages("BrokerB", consumerB); - - LOG.info("consumerA = " + messagesA); - LOG.info("consumerB = " + messagesB); - - messagesA.assertMessagesReceived(0); - messagesB.assertMessagesReceived(1); - - } - - public void testSendRestart() throws Exception { - - Thread.sleep(1000); - - LOG.info("sending message"); - - sendMessages("BrokerA", queue, 1); - - Thread.sleep(3000); - - LOG.info("restarting broker"); - - restartBroker("BrokerA"); - - Thread.sleep(5000); - - LOG.info("consuming message"); - - MessageConsumer consumerA = createConsumer("BrokerA", queue); - MessageConsumer consumerB = createConsumer("BrokerB", queue); - - Thread.sleep(1000); - - MessageIdList messagesA = getConsumerMessages("BrokerA", consumerA); - MessageIdList messagesB = getConsumerMessages("BrokerB", consumerB); - - LOG.info("consumerA = " + messagesA); - LOG.info("consumerB = " + messagesB); - - messagesA.assertMessagesReceived(0); - messagesB.assertMessagesReceived(1); - } - - protected void restartBroker(String brokerName) throws Exception { - destroyBroker("BrokerA"); - BrokerService broker = createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=true&useJmx=false")); - broker.setBrokerId("BrokerA"); - NetworkConnector aTOb = bridgeBrokers(brokers.get("BrokerA").broker, brokers.get("BrokerB").broker, false, 2, true, true); - aTOb.addStaticallyIncludedDestination(queue); - broker.start(); - broker.waitUntilStarted(); - waitForBridgeFormation(); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AMQStackOverFlowTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AMQStackOverFlowTest.java deleted file mode 100644 index bb82e2a372..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AMQStackOverFlowTest.java +++ /dev/null @@ -1,148 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.usecases; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.network.DiscoveryNetworkConnector; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.usage.SystemUsage; -import org.springframework.jms.core.JmsTemplate; -import org.springframework.jms.core.MessageCreator; - -public class AMQStackOverFlowTest extends TestCase { - - private static final String URL1 = "tcp://localhost:61616"; - - private static final String URL2 = "tcp://localhost:61617"; - - public void testStackOverflow() throws Exception { - BrokerService brokerService1 = null; - BrokerService brokerService2 = null; - - try { - brokerService1 = createBrokerService("broker1", URL1, URL2); - brokerService1.start(); - brokerService2 = createBrokerService("broker2", URL2, URL1); - brokerService2.start(); - - final ActiveMQConnectionFactory cf1 = new ActiveMQConnectionFactory(URL1); - cf1.setUseAsyncSend(false); - - final ActiveMQConnectionFactory cf2 = new ActiveMQConnectionFactory(URL2); - cf2.setUseAsyncSend(false); - - final JmsTemplate template1 = new JmsTemplate(cf1); - template1.setReceiveTimeout(10000); - - template1.send("test.q", new MessageCreator() { - - @Override - public Message createMessage(Session session) throws JMSException { - return session.createTextMessage("test"); - } - - }); - - final JmsTemplate template2 = new JmsTemplate(cf2); - template2.setReceiveTimeout(10000); - - final Message m = template2.receive("test.q"); - assertTrue(m instanceof TextMessage); - - final TextMessage tm = (TextMessage) m; - - assertEquals("test", tm.getText()); - - template2.send("test2.q", new MessageCreator() { - - @Override - public Message createMessage(Session session) throws JMSException { - return session.createTextMessage("test2"); - } - }); - - final Message m2 = template1.receive("test2.q"); - assertNotNull(m2); - assertTrue(m2 instanceof TextMessage); - - final TextMessage tm2 = (TextMessage) m2; - - assertEquals("test2", tm2.getText()); - - } finally { - brokerService1.stop(); - brokerService1 = null; - brokerService2.stop(); - brokerService2 = null; - } - } - - private BrokerService createBrokerService(final String brokerName, - final String uri1, - final String uri2) throws Exception { - final BrokerService brokerService = new BrokerService(); - - brokerService.setBrokerName(brokerName); - brokerService.setPersistent(false); - brokerService.setUseJmx(true); - - final SystemUsage memoryManager = new SystemUsage(); - //memoryManager.getMemoryUsage().setLimit(10); - brokerService.setSystemUsage(memoryManager); - - final List policyEntries = new ArrayList<>(); - - final PolicyEntry entry = new PolicyEntry(); - entry.setQueue(">"); - //entry.setMemoryLimit(1); - policyEntries.add(entry); - - final PolicyMap policyMap = new PolicyMap(); - policyMap.setPolicyEntries(policyEntries); - brokerService.setDestinationPolicy(policyMap); - - final TransportConnector tConnector = new TransportConnector(); - tConnector.setUri(new URI(uri1)); - tConnector.setName(brokerName + ".transportConnector"); - brokerService.addConnector(tConnector); - - if (uri2 != null) { - final NetworkConnector nc = new DiscoveryNetworkConnector(new URI("static:" + uri2)); - nc.setBridgeTempDestinations(true); - nc.setBrokerName(brokerName); - //nc.setPrefetchSize(1); - brokerService.addNetworkConnector(nc); - } - - return brokerService; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AbstractTwoBrokerNetworkConnectorWildcardIncludedDestinationTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AbstractTwoBrokerNetworkConnectorWildcardIncludedDestinationTestSupport.java deleted file mode 100644 index 17f5fbc7ed..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AbstractTwoBrokerNetworkConnectorWildcardIncludedDestinationTestSupport.java +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.MessageConsumer; -import java.io.File; -import java.io.IOException; -import java.net.URI; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.DestinationInterceptor; -import org.apache.activemq.broker.region.virtual.VirtualDestination; -import org.apache.activemq.broker.region.virtual.VirtualDestinationInterceptor; -import org.apache.activemq.broker.region.virtual.VirtualTopic; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.store.kahadb.KahaDBStore; -import org.apache.activemq.util.MessageIdList; - -public abstract class AbstractTwoBrokerNetworkConnectorWildcardIncludedDestinationTestSupport extends JmsMultipleBrokersTestSupport { - - protected static final int MESSAGE_COUNT = 1; - boolean dynamicOnly = true; - int networkTTL = 1; - boolean conduit = true; - boolean suppressDuplicateQueueSubscriptions = true; - boolean decreaseNetworkConsumerPriority = true; - - /** - * simple nwob - */ - public void testSimpleNWOB() throws Exception { - - sendReceive("BrokerA", "local.test", false, "BrokerB", "local.test", false, 1, 0); - sendReceive("BrokerA", "local.test", true, "BrokerB", "local.test", true, 1, 0); - sendReceive("BrokerA", "global.test", false, "BrokerB", "global.test", false, 1, 1); - sendReceive("BrokerA", "global.test", true, "BrokerB", "global.test", true, 1, 1); - - } - - /** - * nwob with wild-card subscriptions - */ - public void testSimpleNWOBWithWildcardSubscriptions() throws Exception { - - sendReceive("BrokerA", "local.test.1", false, "BrokerB", "local.test.>", false, 1, 0); - sendReceive("BrokerA", "local.test.2", true, "BrokerB", "local.test.>", true, 1, 0); - sendReceive("BrokerA", "global.test.1", false, "BrokerB", "global.test.>", false, 1, 1); - sendReceive("BrokerA", "global.test.2", true, "BrokerB", "global.test.>", true, 1, 1); - - } - - /** - * nwob with virtual destinations - */ - public void testSimpleNWOBWithVirtualDestinations() throws Exception { - - sendReceive("BrokerA", "local.test", true, "BrokerB", "Consumer.a.local.test", false, 1, 0); - sendReceive("BrokerA", "global.test", true, "BrokerB", "Consumer.a.global.test", false, 1, 1); - - } - - /** - * nwob with virtual destinations and wild-card subscriptions - */ - public void testSimpleNWOBWithVirtualDestinationsAndWildcardSubscriptions() throws Exception { - - sendReceive("BrokerA", "local.test.1", true, "BrokerB", "Consumer.a.local.test.>", false, 1, 0); - sendReceive("BrokerA", "global.test.1", true, "BrokerB", "Consumer.a.global.test.>", false, 1, 1); - - } - - public void sendReceive(String broker1, - String dest1, - boolean topic1, - String broker2, - String dest2, - boolean topic2, - int send, - int expected) throws Exception { - MessageConsumer client = createConsumer(broker2, createDestination(dest2, topic2)); - Thread.sleep(2000); - sendMessages(broker1, createDestination(dest1, topic1), send); - MessageIdList msgs = getConsumerMessages(broker2, client); - msgs.setMaximumDuration(10000); - msgs.waitForMessagesToArrive(send); - assertEquals(expected, msgs.getMessageCount()); - client.close(); - Thread.sleep(1000); - } - - protected abstract void addIncludedDestination(NetworkConnector networkConnector); - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - String options = new String("?useJmx=false&deleteAllMessagesOnStartup=true"); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61616)/BrokerA" + options)); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61617)/BrokerB" + options)); - - // Setup broker networks - NetworkConnector nc = bridgeBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduit); - nc.setDecreaseNetworkConsumerPriority(decreaseNetworkConsumerPriority); - nc.setSuppressDuplicateQueueSubscriptions(suppressDuplicateQueueSubscriptions); - - addIncludedDestination(nc); - - nc = bridgeBrokers("BrokerB", "BrokerA", dynamicOnly, networkTTL, conduit); - nc.setDecreaseNetworkConsumerPriority(decreaseNetworkConsumerPriority); - nc.setSuppressDuplicateQueueSubscriptions(suppressDuplicateQueueSubscriptions); - - addIncludedDestination(nc); - - startAllBrokers(); - - } - - private BrokerService createAndConfigureBroker(URI uri) throws Exception { - BrokerService broker = createBroker(uri); - - configurePersistenceAdapter(broker); - - // make all topics virtual and consumers use the default prefix - VirtualDestinationInterceptor virtualDestinationInterceptor = new VirtualDestinationInterceptor(); - virtualDestinationInterceptor.setVirtualDestinations(new VirtualDestination[]{new VirtualTopic()}); - DestinationInterceptor[] destinationInterceptors = new DestinationInterceptor[]{virtualDestinationInterceptor}; - broker.setDestinationInterceptors(destinationInterceptors); - return broker; - } - - protected void configurePersistenceAdapter(BrokerService broker) throws IOException { - File dataFileDir = new File("target/test-amq-data/kahadb/" + broker.getBrokerName()); - KahaDBStore kaha = new KahaDBStore(); - kaha.setDirectory(dataFileDir); - broker.setPersistenceAdapter(kaha); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AdvisoryTopicCleanUpTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AdvisoryTopicCleanUpTest.java deleted file mode 100644 index fa34300bf4..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AdvisoryTopicCleanUpTest.java +++ /dev/null @@ -1,164 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQDestination; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; - -public class AdvisoryTopicCleanUpTest { - - private static final Logger LOG = LoggerFactory.getLogger(AdvisoryTopicCleanUpTest.class); - - private BrokerService broker; - private String connectionUri; - - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(connectionUri + "?jms.redeliveryPolicy.maximumRedeliveries=2"); - } - - @Before - public void setUp() throws Exception { - createBroker(); - } - - @After - public void tearDown() throws Exception { - destroyBroker(); - } - - private void createBroker() throws Exception { - broker = new BrokerService(); - broker.setPersistent(false); - broker.setDeleteAllMessagesOnStartup(true); - broker.setUseJmx(true); - connectionUri = broker.addConnector("tcp://localhost:0").getPublishableConnectString(); - - PolicyEntry policy = new PolicyEntry(); - policy.setAdvisoryForFastProducers(true); - policy.setAdvisoryForConsumed(true); - policy.setAdvisoryForDelivery(true); - policy.setAdvisoryForDiscardingMessages(true); - policy.setAdvisoryForSlowConsumers(true); - policy.setAdvisoryWhenFull(true); - policy.setProducerFlowControl(false); - PolicyMap pMap = new PolicyMap(); - pMap.setDefaultEntry(policy); - broker.setDestinationPolicy(pMap); - - broker.start(); - } - - protected Connection createConnection() throws Exception { - Connection con = createConnectionFactory().createConnection(); - con.start(); - return con; - } - - private void destroyBroker() throws Exception { - if (broker != null) - broker.stop(); - } - - @Test - public void testAdvisoryTopic() throws Exception { - Connection connection = createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination queue = (ActiveMQDestination) session.createQueue("AdvisoryTopicCleanUpTestQueue"); - MessageProducer prod = session.createProducer(queue); - Message message = session.createMessage(); - prod.send(message); - message = session.createMessage(); - prod.send(message); - message = session.createMessage(); - prod.send(message, Message.DEFAULT_DELIVERY_MODE, Message.DEFAULT_PRIORITY, 1000); - connection.close(); - connection = createConnection(); - - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(queue); - message = consumer.receive(60 * 1000); - message.acknowledge(); - connection.close(); - connection = null; - - for (int i = 0; i < 2; i++) { - connection = createConnection(); - session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - consumer = session.createConsumer(queue); - message = consumer.receive(60 * 1000); - session.rollback(); - connection.close(); - connection = null; - } - - Thread.sleep(2 * 1000); - - connection = createConnection(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - consumer = session.createConsumer(queue); - message = consumer.receive(1000); - if (message != null) - message.acknowledge(); - connection.close(); - connection = null; - - TimeUnit.SECONDS.sleep(1); - - ActiveMQDestination dests[] = broker.getRegionBroker().getDestinations(); - - for (ActiveMQDestination destination : dests) { - String name = destination.getPhysicalName(); - if (name.contains(queue.getPhysicalName())) { - LOG.info("Destination on Broker before removing the Queue: " + name); - } - } - - dests = broker.getRegionBroker().getDestinations(); - if (dests == null) { - fail("Should have Destination for: " + queue.getPhysicalName()); - } - - broker.getAdminView().removeQueue(queue.getPhysicalName()); - - dests = broker.getRegionBroker().getDestinations(); - if (dests != null) { - for (ActiveMQDestination destination : dests) { - String name = destination.getPhysicalName(); - LOG.info("Destination on broker after removing the Queue: " + name); - assertFalse("Advisory topic should not exist. " + name, name.startsWith("ActiveMQ.Advisory") && name.contains(queue.getPhysicalName())); - } - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AdvisoryTopicDeletionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AdvisoryTopicDeletionTest.java deleted file mode 100644 index 520142a3c4..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AdvisoryTopicDeletionTest.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.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.TestSupport; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQDestination; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class AdvisoryTopicDeletionTest extends TestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(AdvisoryTopicDeletionTest.class); - - private BrokerService broker; - private Connection connection; - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://" + getName()); - } - - @Override - protected void setUp() throws Exception { - createBroker(); - topic = false; - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - destroyBroker(); - } - - private void createBroker() throws Exception { - broker = BrokerFactory.createBroker("broker:(vm://localhost)"); - broker.setPersistent(false); - broker.setBrokerName(getName()); - broker.start(); - - connection = createConnection(); - } - - @Override - protected Connection createConnection() throws Exception { - Connection con = super.createConnection(); - con.start(); - return con; - } - - private void destroyBroker() throws Exception { - if (connection != null) - connection.close(); - if (broker != null) - broker.stop(); - } - - public void doTest() throws Exception { - Destination dest = createDestination(); - - Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageConsumer consumer = consumerSession.createConsumer(dest); - - MessageProducer prod = producerSession.createProducer(dest); - Message message = producerSession.createMessage(); - prod.send(message); - - consumer.receive(60 * 1000); - connection.close(); - connection = null; - - if (topic) { - broker.getAdminView().removeTopic(((ActiveMQDestination) dest).getPhysicalName()); - } else { - broker.getAdminView().removeQueue(((ActiveMQDestination) dest).getPhysicalName()); - } - - ActiveMQDestination dests[] = broker.getRegionBroker().getDestinations(); - int matchingDestinations = 0; - for (ActiveMQDestination destination : dests) { - String name = destination.getPhysicalName(); - LOG.debug("Found destination " + name); - if (name.startsWith("ActiveMQ.Advisory") && name.contains(getDestinationString())) { - matchingDestinations++; - } - } - - assertEquals("No matching destinations should be found", 0, matchingDestinations); - } - - public void testTopic() throws Exception { - topic = true; - doTest(); - } - - public void testQueue() throws Exception { - topic = false; - doTest(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AuthorizationFromAdminViewTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AuthorizationFromAdminViewTest.java deleted file mode 100644 index 892c27d00b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/AuthorizationFromAdminViewTest.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.activemq.usecases; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerPlugin; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.security.AuthorizationPlugin; -import org.apache.activemq.security.SimpleAuthorizationMap; - -public class AuthorizationFromAdminViewTest extends org.apache.activemq.TestSupport { - - private BrokerService broker; - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://" + getName()); - } - - @Override - protected void setUp() throws Exception { - createBroker(); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - destroyBroker(); - } - - private void createBroker() throws Exception { - broker = BrokerFactory.createBroker("broker:(vm://localhost)"); - broker.setPersistent(false); - broker.setBrokerName(getName()); - - AuthorizationPlugin plugin = new AuthorizationPlugin(); - plugin.setMap(new SimpleAuthorizationMap()); - BrokerPlugin[] plugins = new BrokerPlugin[]{plugin}; - broker.setPlugins(plugins); - - broker.start(); - } - - private void destroyBroker() throws Exception { - if (broker != null) - broker.stop(); - } - - public void testAuthorizationFromAdminView() throws Exception { - broker.getAdminView().addQueue(getDestinationString()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BacklogNetworkCrossTalkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BacklogNetworkCrossTalkTest.java deleted file mode 100644 index ae47ceba83..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BacklogNetworkCrossTalkTest.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.activemq.usecases; - -import javax.jms.MessageConsumer; -import java.net.URI; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.util.MessageIdList; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class BacklogNetworkCrossTalkTest extends JmsMultipleBrokersTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(BacklogNetworkCrossTalkTest.class); - - @Override - protected BrokerService createBroker(String brokerName) throws Exception { - BrokerService broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(true); - broker.setPersistent(true); - broker.setUseJmx(false); - broker.setBrokerName(brokerName); - broker.addConnector(new URI(AUTO_ASSIGN_TRANSPORT)); - brokers.put(brokerName, new BrokerItem(broker)); - - return broker; - } - - public void testProduceConsume() throws Exception { - createBroker("A"); - createBroker("B"); - - NetworkConnector nc = bridgeBrokers("A", "B"); - nc.setDuplex(true); - nc.setDispatchAsync(false); - startAllBrokers(); - - waitForBridgeFormation(); - - final int numMessages = 10000; - // Create queue - ActiveMQDestination destA = createDestination("AAA", false); - sendMessages("A", destA, numMessages); - - ActiveMQDestination destB = createDestination("BBB", false); - sendMessages("B", destB, numMessages); - - // consume across network - LOG.info("starting consumers.."); - - // Setup consumers - MessageConsumer clientA = createConsumer("A", destB); - // Setup consumers - MessageConsumer clientB = createConsumer("B", destA); - - final long maxWait = 5 * 60 * 1000L; - MessageIdList listA = getConsumerMessages("A", clientA); - listA.setMaximumDuration(maxWait); - listA.waitForMessagesToArrive(numMessages); - - MessageIdList listB = getConsumerMessages("B", clientB); - listB.setMaximumDuration(maxWait); - listB.waitForMessagesToArrive(numMessages); - - assertEquals("got all on A" + listA.getMessageCount(), numMessages, listA.getMessageCount()); - - assertEquals("got all on B" + listB.getMessageCount(), numMessages, listB.getMessageCount()); - - } - - @Override - public void setUp() throws Exception { - messageSize = 5000; - super.setMaxTestTime(10 * 60 * 1000); - super.setAutoFail(true); - super.setUp(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BatchedMessagePriorityConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BatchedMessagePriorityConsumerTest.java deleted file mode 100644 index 72aebb462c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BatchedMessagePriorityConsumerTest.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.activemq.usecases; - -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; - -import org.apache.activemq.JmsTestSupport; -import org.apache.activemq.command.ActiveMQDestination; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class BatchedMessagePriorityConsumerTest extends JmsTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(BatchedMessagePriorityConsumerTest.class); - - public void testBatchWithLowPriorityFirstAndClientSupport() throws Exception { - doTestBatchWithLowPriorityFirst(true); - } - - public void testBatchWithLowPriorityFirstAndClientSupportOff() throws Exception { - doTestBatchWithLowPriorityFirst(false); - } - - public void doTestBatchWithLowPriorityFirst(boolean clientPrioritySupport) throws Exception { - - connection.start(); - connection.setMessagePrioritySupported(clientPrioritySupport); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE); - - MessageProducer producer = session.createProducer(destination); - producer.setPriority(0); - sendMessages(session, producer, 2); - producer.close(); - - MessageProducer producer2 = session.createProducer(destination); - producer2.setPriority(9); - sendMessages(session, producer2, 3); - producer2.close(); - - session.close(); - - Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED); - MessageConsumer messageConsumer = consumerSession.createConsumer(destination); - - for (int i = 0; i < 5; i++) { - Message message = messageConsumer.receive(4000); - LOG.info("MessageID: " + message.getJMSMessageID()); - } - - consumerSession.commit(); - consumerSession.close(); - - // should be nothing left - consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - messageConsumer = consumerSession.createConsumer(destination); - - assertNull("No message left", messageConsumer.receive(1000)); - - consumerSession.close(); - - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrokerQueueNetworkWithDisconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrokerQueueNetworkWithDisconnectTest.java deleted file mode 100644 index 0aba904669..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrokerQueueNetworkWithDisconnectTest.java +++ /dev/null @@ -1,262 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Destination; -import javax.jms.MessageConsumer; -import javax.jms.TextMessage; -import java.net.URI; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import junit.framework.Test; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerPlugin; -import org.apache.activemq.broker.BrokerPluginSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.ConnectionContext; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.command.ConnectionInfo; -import org.apache.activemq.network.DiscoveryNetworkConnector; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.transport.vm.VMTransportFactory; -import org.apache.activemq.util.MessageIdList; -import org.apache.activemq.util.SocketProxy; -import org.apache.activemq.util.Wait; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class BrokerQueueNetworkWithDisconnectTest extends JmsMultipleBrokersTestSupport { - - private static final Log LOG = LogFactory.getLog(BrokerQueueNetworkWithDisconnectTest.class); - private static final int NETWORK_DOWN_TIME = 5000; - protected static final int MESSAGE_COUNT = 200; - private static final String HUB = "HubBroker"; - private static final String SPOKE = "SpokeBroker"; - private SocketProxy socketProxy; - private long networkDownTimeStart; - public boolean useDuplexNetworkBridge = true; - public boolean simulateStalledNetwork; - private long inactiveDuration = 1000; - private boolean useSocketProxy = true; - - public void initCombosForTestSendOnAReceiveOnBWithTransportDisconnect() { - addCombinationValues("useDuplexNetworkBridge", new Object[]{Boolean.TRUE, Boolean.FALSE}); - addCombinationValues("simulateStalledNetwork", new Object[]{Boolean.TRUE}); - } - - public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception { - bridgeBrokers(SPOKE, HUB); - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - MessageConsumer client = createConsumer(HUB, dest); - - // allow subscription information to flow back to Spoke - sleep(600); - - // Send messages - sendMessages(SPOKE, dest, MESSAGE_COUNT); - - MessageIdList msgs = getConsumerMessages(HUB, client); - msgs.waitForMessagesToArrive(MESSAGE_COUNT); - - assertTrue("At least message " + MESSAGE_COUNT + - " must be received, duplicates are expected, count=" + msgs.getMessageCount(), MESSAGE_COUNT <= msgs.getMessageCount()); - } - - public void testNoStuckConnectionsWithTransportDisconnect() throws Exception { - inactiveDuration = 60000L; - useDuplexNetworkBridge = true; - - bridgeBrokers(SPOKE, HUB); - - final BrokerItem hub = brokers.get(HUB); - hub.broker.setPlugins(new BrokerPlugin[]{new BrokerPluginSupport() { - int sleepCount = 2; - - @Override - public void removeConnection(ConnectionContext context, - ConnectionInfo info, - Throwable error) throws Exception { - try { - while (--sleepCount >= 0) { - LOG.info("sleeping for a bit in close impl to simulate load where reconnect fails due to a pending close"); - TimeUnit.SECONDS.sleep(2); - } - } catch (Exception ignored) { - } - super.removeConnection(context, info, error); - } - }}); - startAllBrokers(); - waitForBridgeFormation(); - - // kill the initiator side, leaving remote end intact - // simulate async network breakage - // remote side will need to spot duplicate network and stop/kill the original - for (int i = 0; i < 3; i++) { - socketProxy.halfClose(); - sleep(10000); - } - // wait for full reformation of bridge - // verify no extra connections - boolean allGood = Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - long numConnections = hub.broker.getTransportConnectors().get(0).getConnections().size(); - LOG.info("Num connetions:" + numConnections); - return numConnections == 1; - } - }); - if (!allGood) { - dumpAllThreads("ExtraHubConnection"); - } - assertTrue("should be only one transport connection for the single duplex network connector", allGood); - - allGood = Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - long numVmConnections = VMTransportFactory.SERVERS.get(HUB).getConnectionCount(); - LOG.info("Num VM connetions:" + numVmConnections); - return numVmConnections == 2; - } - }); - if (!allGood) { - dumpAllThreads("ExtraHubVMConnection"); - } - assertTrue("should be only 2 vm connections for the single network duplex network connector", allGood); - } - - public void testTwoDuplexNCsAreAllowed() throws Exception { - useDuplexNetworkBridge = true; - useSocketProxy = false; - - NetworkConnector connector = bridgeBrokers(SPOKE, HUB); - connector.setName("FirstDuplex"); - connector = bridgeBrokers(SPOKE, HUB); - connector.setName("SecondDuplex"); - - startAllBrokers(); - waitForBridgeFormation(); - - BrokerItem hub = brokers.get(HUB); - assertEquals("Has two transport Connectors", 2, hub.broker.getTransportConnectors().get(0).getConnections().size()); - } - - @Override - protected void startAllBrokers() throws Exception { - // Ensure HUB is started first so bridge will be active from the get go - BrokerItem brokerItem = brokers.get(HUB); - brokerItem.broker.start(); - brokerItem = brokers.get(SPOKE); - brokerItem.broker.start(); - sleep(600); - } - - @Override - public void setUp() throws Exception { - networkDownTimeStart = 0; - inactiveDuration = 1000; - useSocketProxy = true; - super.setAutoFail(true); - super.setUp(); - final String options = "?persistent=true&useJmx=false&deleteAllMessagesOnStartup=true"; - createBroker(new URI("broker:(tcp://localhost:61617)/" + HUB + options)); - createBroker(new URI("broker:(tcp://localhost:61616)/" + SPOKE + options)); - } - - @Override - public void tearDown() throws Exception { - super.tearDown(); - if (socketProxy != null) { - socketProxy.close(); - } - } - - public static Test suite() { - return suite(BrokerQueueNetworkWithDisconnectTest.class); - } - - @Override - protected void onSend(int i, TextMessage msg) { - sleep(50); - if (i == 50 || i == 150) { - if (simulateStalledNetwork) { - socketProxy.pause(); - } else { - socketProxy.close(); - } - networkDownTimeStart = System.currentTimeMillis(); - } else if (networkDownTimeStart > 0) { - // restart after NETWORK_DOWN_TIME seconds - if (networkDownTimeStart + NETWORK_DOWN_TIME < System.currentTimeMillis()) { - if (simulateStalledNetwork) { - socketProxy.goOn(); - } else { - socketProxy.reopen(); - } - networkDownTimeStart = 0; - } else { - // slow message production to allow bridge to recover and limit message duplication - sleep(500); - } - } - super.onSend(i, msg); - } - - private void sleep(int milliSecondTime) { - try { - Thread.sleep(milliSecondTime); - } catch (InterruptedException igonred) { - } - } - - @Override - protected NetworkConnector bridgeBrokers(BrokerService localBroker, - BrokerService remoteBroker, - boolean dynamicOnly, - int networkTTL, - boolean conduit, - boolean failover) throws Exception { - List transportConnectors = remoteBroker.getTransportConnectors(); - URI remoteURI; - if (!transportConnectors.isEmpty()) { - remoteURI = transportConnectors.get(0).getConnectUri(); - if (useSocketProxy) { - socketProxy = new SocketProxy(remoteURI); - remoteURI = socketProxy.getUrl(); - } - DiscoveryNetworkConnector connector = new DiscoveryNetworkConnector(new URI("static:(" + remoteURI + "?wireFormat.maxInactivityDuration=" + inactiveDuration + "&wireFormat.maxInactivityDurationInitalDelay=" + inactiveDuration + ")?useExponentialBackOff=false")); - connector.setDynamicOnly(dynamicOnly); - connector.setNetworkTTL(networkTTL); - localBroker.addNetworkConnector(connector); - maxSetupTime = 2000; - if (useDuplexNetworkBridge) { - connector.setDuplex(true); - } - return connector; - } else { - throw new Exception("Remote broker has no registered connectors."); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrowseDLQTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrowseDLQTest.java deleted file mode 100644 index d365ca5e00..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrowseDLQTest.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.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.JMSException; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.OpenDataException; -import javax.management.openmbean.TabularData; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.jmx.QueueViewMBean; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQQueue; -import org.junit.After; -import org.junit.Test; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -/** - * @author Christian Posta - */ -public class BrowseDLQTest { - - private static final int NUM_MESSAGES = 100; - private BrokerService brokerService; - private ActiveMQQueue testQueue = new ActiveMQQueue("TEST.FOO"); - private ActiveMQQueue dlq = new ActiveMQQueue("ActiveMQ.DLQ"); - - @Test - public void testCannotBrowseDLQAsTable() throws Exception { - startBroker(); - // send 100 messages to queue with TTL of 1 second - sendMessagesToBeExpired(); - - // let's let the messages expire - TimeUnit.SECONDS.sleep(2); - - assertCanBrowse(); - } - - private void assertCanBrowse() throws MalformedObjectNameException, OpenDataException { - ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=ActiveMQ.DLQ"); - QueueViewMBean queue = (QueueViewMBean) brokerService.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); - // make sure we have messages here - assertTrue(queue.getQueueSize() > 0); - - CompositeData[] regularBrowse = queue.browse(); - assertNotNull(regularBrowse); - - TabularData tableData = queue.browseAsTable(); - assertNotNull(tableData); - - } - - @After - public void tearDown() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } - - private void startBroker() throws Exception { - brokerService = BrokerFactory.createBroker("broker:()/localhost?deleteAllMessagesOnStartup=true"); - - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policyEntry = new PolicyEntry(); - policyEntry.setExpireMessagesPeriod(1000); - policyMap.setDefaultEntry(policyEntry); - brokerService.setDestinationPolicy(policyMap); - brokerService.start(); - brokerService.waitUntilStarted(); - } - - private void sendMessagesToBeExpired() throws JMSException, InterruptedException { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(testQueue); - for (int i = 0; i < NUM_MESSAGES; i++) { - producer.send(testQueue, session.createTextMessage("Hello world #" + i), DeliveryMode.PERSISTENT, 4, 500); - } - connection.close(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrowseOverNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrowseOverNetworkTest.java deleted file mode 100644 index d77642e630..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/BrowseOverNetworkTest.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.activemq.usecases; - -import javax.jms.Destination; -import javax.jms.MessageConsumer; -import javax.jms.QueueBrowser; -import java.net.URI; -import java.util.Arrays; -import java.util.Enumeration; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.QueueSubscription; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQTextMessage; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.util.MessageIdList; -import org.apache.activemq.util.Wait; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.ClassPathResource; - -public class BrowseOverNetworkTest extends JmsMultipleBrokersTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(QueueSubscription.class); - protected static final int MESSAGE_COUNT = 10; - - public void testBrowse() throws Exception { - createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=false")); - createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=false")); - - bridgeBrokers("BrokerA", "BrokerB"); - - startAllBrokers(); - - Destination dest = createDestination("TEST.FOO", false); - - sendMessages("BrokerA", dest, MESSAGE_COUNT); - - Thread.sleep(1000); - - int browsed = browseMessages("BrokerB", dest); - - Thread.sleep(1000); - - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - msgsA.waitForMessagesToArrive(MESSAGE_COUNT); - - Thread.sleep(1000); - MessageConsumer clientB = createConsumer("BrokerB", dest); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - msgsB.waitForMessagesToArrive(MESSAGE_COUNT); - - LOG.info("A+B: " + msgsA.getMessageCount() + "+" + msgsB.getMessageCount()); - assertEquals("Consumer on Broker A, should've consumed all messages", MESSAGE_COUNT, msgsA.getMessageCount()); - assertEquals("Broker B shouldn't get any messages", 0, browsed); - } - - public void testConsumerInfo() throws Exception { - createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker1.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker2.xml")); - - startAllBrokers(); - - brokers.get("broker1").broker.waitUntilStarted(); - - Destination dest = createDestination("QUEUE.A,QUEUE.B", false); - - int broker1 = browseMessages("broker1", dest); - assertEquals("Browsed a message on an empty queue", 0, broker1); - Thread.sleep(1000); - int broker2 = browseMessages("broker2", dest); - assertEquals("Browsed a message on an empty queue", 0, broker2); - - } - - public class Browser extends Thread { - - String broker; - Destination dest; - int totalCount; - final int expect; - QueueBrowser browser = null; - MessageConsumer consumer = null; - boolean consume = false; - - public Browser(String broker, Destination dest, int expect) { - this.broker = broker; - this.dest = dest; - this.expect = expect; - } - - @Override - public void run() { - int retries = 0; - while (retries++ < 20 && totalCount != expect) { - try { - QueueBrowser browser = createBrowser(broker, dest); - int count = browseMessages(browser, broker); - if (consume) { - if (count != 0) { - MessageConsumer consumer = createSyncConsumer(broker, dest); - totalCount += count; - for (int i = 0; i < count; i++) { - ActiveMQTextMessage message = (ActiveMQTextMessage) consumer.receive(1000); - if (message == null) - break; - LOG.info(broker + " consumer: " + message.getText() + " " + message.getDestination() + " " + message.getMessageId() + " " + Arrays.toString(message.getBrokerPath())); - } - } - } else { - totalCount = count; - } - LOG.info("browser '" + broker + "' browsed " + totalCount); - - Thread.sleep(1000); - } catch (Exception e) { - LOG.info("Exception browsing " + e, e); - } finally { - try { - if (browser != null) { - browser.close(); - } - if (consumer != null) { - consumer.close(); - } - } catch (Exception e) { - LOG.info("Exception closing browser " + e, e); - } - } - } - } - - public int getTotalCount() { - return totalCount; - } - } - - protected NetworkConnector bridgeBrokersWithIncludedDestination(String localBrokerName, - String remoteBrokerName, - ActiveMQDestination included, - ActiveMQDestination excluded) throws Exception { - NetworkConnector nc = bridgeBrokers(localBrokerName, remoteBrokerName, false, 4, true); - nc.addStaticallyIncludedDestination(included); - if (excluded != null) { - nc.addExcludedDestination(excluded); - } - nc.setPrefetchSize(1); - return nc; - } - - public void testAMQ3020() throws Exception { - createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker1A.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker1B.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker2A.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker2B.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker3A.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/browse-broker3B.xml")); - - brokers.get("broker-1A").broker.waitUntilStarted(); - brokers.get("broker-2A").broker.waitUntilStarted(); - brokers.get("broker-3A").broker.waitUntilStarted(); - - for (BrokerItem brokerItem : brokers.values()) { - final BrokerService broker = brokerItem.broker; - waitForBridgeFormation(broker, 1, 0); - waitForBridgeFormation(broker, 1, 1); - waitForBridgeFormation(broker, 1, 2); - waitForBridgeFormation(broker, 1, 3); - waitForBridgeFormation(broker, 1, 4); - } - - Destination composite = createDestination("PROD.FUSESOURCE.3.A,PROD.FUSESOURCE.3.B", false); - - final Browser browser1 = new Browser("broker-3A", composite, MESSAGE_COUNT); - browser1.start(); - - final Browser browser2 = new Browser("broker-3B", composite, MESSAGE_COUNT); - browser2.start(); - - LOG.info("Sending messages to broker-1A"); - sendMessages("broker-1A", composite, MESSAGE_COUNT); - LOG.info("Message sent to broker-1A"); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return browser1.getTotalCount() == MESSAGE_COUNT; - } - }); - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return browser2.getTotalCount() == MESSAGE_COUNT; - } - }); - - browser1.join(); - browser2.join(); - - LOG.info("broker-3A browsed " + browser1.getTotalCount()); - LOG.info("broker-3B browsed " + browser2.getTotalCount()); - - assertEquals(MESSAGE_COUNT * 2, browser1.getTotalCount() + browser2.getTotalCount()); - - } - - protected int browseMessages(QueueBrowser browser, String name) throws Exception { - Enumeration msgs = browser.getEnumeration(); - int browsedMessage = 0; - while (msgs.hasMoreElements()) { - browsedMessage++; - ActiveMQTextMessage message = (ActiveMQTextMessage) msgs.nextElement(); - LOG.info(name + " browsed: " + message.getText() + " " + message.getDestination() + " " + message.getMessageId() + " " + Arrays.toString(message.getBrokerPath())); - } - return browsedMessage; - } - - protected int browseMessages(String broker, Destination dest) throws Exception { - QueueBrowser browser = createBrowser(broker, dest); - int browsedMessage = browseMessages(browser, "browser"); - browser.close(); - return browsedMessage; - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ChangeSentMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ChangeSentMessageTest.java deleted file mode 100644 index 8e46da2016..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ChangeSentMessageTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.ObjectMessage; -import javax.jms.Session; -import java.util.HashMap; - -import org.apache.activemq.test.TestSupport; - -/** - * - */ -public class ChangeSentMessageTest extends TestSupport { - - private static final int COUNT = 200; - private static final String VALUE_NAME = "value"; - - /** - * test Object messages can be changed after sending with no side-affects - * - * @throws Exception - */ - @SuppressWarnings("rawtypes") - public void testDoChangeSentMessage() throws Exception { - Destination destination = createDestination("test-" + ChangeSentMessageTest.class.getName()); - Connection connection = createConnection(); - connection.start(); - Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = consumerSession.createConsumer(destination); - Session publisherSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = publisherSession.createProducer(destination); - HashMap map = new HashMap<>(); - ObjectMessage message = publisherSession.createObjectMessage(); - for (int i = 0; i < COUNT; i++) { - map.put(VALUE_NAME, Integer.valueOf(i)); - message.setObject(map); - producer.send(message); - assertTrue(message.getObject() == map); - } - for (int i = 0; i < COUNT; i++) { - ObjectMessage msg = (ObjectMessage) consumer.receive(); - HashMap receivedMap = (HashMap) msg.getObject(); - Integer intValue = (Integer) receivedMap.get(VALUE_NAME); - assertTrue(intValue.intValue() == i); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ChangeSessionDeliveryModeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ChangeSessionDeliveryModeTest.java deleted file mode 100644 index 229ee4367b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ChangeSessionDeliveryModeTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.IllegalStateException; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.Session; - -import org.apache.activemq.test.TestSupport; - -/** - * - */ -public class ChangeSessionDeliveryModeTest extends TestSupport implements MessageListener { - - /** - * test following condition- which are defined by JMS Spec 1.1: - * MessageConsumers cannot use a MessageListener and receive() from the same - * session - * - * @throws Exception - */ - public void testDoChangeSessionDeliveryMode() throws Exception { - Destination destination = createDestination("foo.bar"); - Connection connection = createConnection(); - connection.start(); - Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer1 = consumerSession.createConsumer(destination); - consumer1.setMessageListener(this); - MessageConsumer consumer2 = consumerSession.createConsumer(destination); - - try { - consumer2.receive(10); - fail("Did not receive expected exception."); - } catch (JMSException e) { - assertTrue(e instanceof IllegalStateException); - } - } - - @Override - public void onMessage(Message msg) { - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ClientRebalanceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ClientRebalanceTest.java deleted file mode 100644 index 3c13b9534f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ClientRebalanceTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.log4j.Logger; -import org.springframework.core.io.ClassPathResource; - -public class ClientRebalanceTest extends JmsMultipleBrokersTestSupport { - - private static final Logger LOG = Logger.getLogger(ClientRebalanceTest.class); - private static final String QUEUE_NAME = "Test.ClientRebalanceTest"; - - @Override - protected void setUp() throws Exception { - setAutoFail(true); - super.setUp(); - } - - public void testRebalance() throws Exception { - createBroker(new ClassPathResource("org/apache/activemq/usecases/rebalance-broker1.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/rebalance-broker2.xml")); - - startAllBrokers(); - - brokers.get("b1").broker.waitUntilStarted(); - - LOG.info("Starting connection"); - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("failover:(tcp://localhost:61616,tcp://localhost:61617)?randomize=false"); - Connection conn = factory.createConnection(); - conn.start(); - Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue theQueue = session.createQueue(QUEUE_NAME); - MessageProducer producer = session.createProducer(theQueue); - MessageConsumer consumer = session.createConsumer(theQueue); - Message message = session.createTextMessage("Test message"); - producer.send(message); - Message msg = consumer.receive(2000); - assertNotNull(msg); - - // introduce third broker - createBroker(new ClassPathResource("org/apache/activemq/usecases/rebalance-broker3.xml")); - brokers.get("b3").broker.waitUntilStarted(); - - Thread.sleep(3000); - - LOG.info("Stopping broker 1"); - - brokers.get("b1").broker.stop(); - brokers.get("b1").broker.waitUntilStopped(); - - Thread.sleep(3000); - // should reconnect to some of the remaining brokers - producer.send(message); - msg = consumer.receive(2000); - assertNotNull(msg); - - LOG.info("Stopping broker 2"); - - brokers.get("b2").broker.stop(); - brokers.get("b2").broker.waitUntilStopped(); - - // should reconnect to broker3 - producer.send(message); - msg = consumer.receive(2000); - assertNotNull(msg); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CompositeConsumeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CompositeConsumeTest.java deleted file mode 100644 index c07f0dd1b1..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CompositeConsumeTest.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.activemq.usecases; - -import javax.jms.Destination; -import javax.jms.Message; - -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.test.JmsTopicSendReceiveWithTwoConnectionsTest; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class CompositeConsumeTest extends JmsTopicSendReceiveWithTwoConnectionsTest { - - private static final Logger LOG = LoggerFactory.getLogger(CompositeConsumeTest.class); - - @Override - public void testSendReceive() throws Exception { - messages.clear(); - - Destination[] destinations = getDestinations(); - int destIdx = 0; - - for (int i = 0; i < data.length; i++) { - Message message = session.createTextMessage(data[i]); - - if (verbose) { - LOG.info("About to send a message: " + message + " with text: " + data[i]); - } - - producer.send(destinations[destIdx], message); - - if (++destIdx >= destinations.length) { - destIdx = 0; - } - } - - assertMessagesAreReceived(); - } - - /** - * Returns the subscription subject - */ - @Override - protected String getSubject() { - return getPrefix() + "FOO.BAR," + getPrefix() + "FOO.X.Y," + getPrefix() + "BAR.>"; - } - - /** - * Returns the destinations on which we publish - */ - protected Destination[] getDestinations() { - return new Destination[]{new ActiveMQTopic(getPrefix() + "FOO.BAR"), new ActiveMQTopic(getPrefix() + "BAR.WHATNOT.XYZ"), new ActiveMQTopic(getPrefix() + "FOO.X.Y")}; - } - - protected String getPrefix() { - return super.getSubject() + "."; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CompositePublishTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CompositePublishTest.java deleted file mode 100644 index aa2e3c1e10..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CompositePublishTest.java +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.Session; -import java.util.List; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.test.JmsSendReceiveTestSupport; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class CompositePublishTest extends JmsSendReceiveTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(CompositePublishTest.class); - - protected Connection sendConnection; - protected Connection receiveConnection; - protected Session receiveSession; - protected MessageConsumer[] consumers; - @SuppressWarnings("rawtypes") - protected List[] messageLists; - - @SuppressWarnings("unchecked") - @Override - protected void setUp() throws Exception { - super.setUp(); - - connectionFactory = createConnectionFactory(); - - sendConnection = createConnection(); - sendConnection.start(); - - receiveConnection = createConnection(); - receiveConnection.start(); - - LOG.info("Created sendConnection: " + sendConnection); - LOG.info("Created receiveConnection: " + receiveConnection); - - session = sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - receiveSession = receiveConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - LOG.info("Created sendSession: " + session); - LOG.info("Created receiveSession: " + receiveSession); - - producer = session.createProducer(null); - - LOG.info("Created producer: " + producer); - - if (topic) { - consumerDestination = session.createTopic(getConsumerSubject()); - producerDestination = session.createTopic(getProducerSubject()); - } else { - consumerDestination = session.createQueue(getConsumerSubject()); - producerDestination = session.createQueue(getProducerSubject()); - } - - LOG.info("Created consumer destination: " + consumerDestination + " of type: " + consumerDestination.getClass()); - LOG.info("Created producer destination: " + producerDestination + " of type: " + producerDestination.getClass()); - - Destination[] destinations = getDestinations(); - consumers = new MessageConsumer[destinations.length]; - messageLists = new List[destinations.length]; - for (int i = 0; i < destinations.length; i++) { - Destination dest = destinations[i]; - messageLists[i] = createConcurrentList(); - consumers[i] = receiveSession.createConsumer(dest); - consumers[i].setMessageListener(createMessageListener(i, messageLists[i])); - } - - LOG.info("Started connections"); - } - - protected MessageListener createMessageListener(int i, final List messageList) { - return new MessageListener() { - @Override - public void onMessage(Message message) { - consumeMessage(message, messageList); - } - }; - } - - /** - * Returns the subject on which we publish - */ - @Override - protected String getSubject() { - return getPrefix() + "FOO.BAR," + getPrefix() + "FOO.X.Y"; - } - - /** - * Returns the destinations to which we consume - */ - protected Destination[] getDestinations() { - return new Destination[]{new ActiveMQTopic(getPrefix() + "FOO.BAR"), new ActiveMQTopic(getPrefix() + "FOO.*"), new ActiveMQTopic(getPrefix() + "FOO.X.Y")}; - } - - protected String getPrefix() { - return super.getSubject() + "."; - } - - @SuppressWarnings("unchecked") - @Override - protected void assertMessagesAreReceived() throws JMSException { - waitForMessagesToBeDelivered(); - int size = messageLists.length; - for (int i = 0; i < size; i++) { - LOG.info("Message list: " + i + " contains: " + messageLists[i].size() + " message(s)"); - } - size = messageLists.length; - for (int i = 0; i < size; i++) { - assertMessagesReceivedAreValid(messageLists[i]); - } - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() { - return new ActiveMQConnectionFactory("vm://localhost"); - } - - @Override - protected void tearDown() throws Exception { - session.close(); - receiveSession.close(); - - sendConnection.close(); - receiveConnection.close(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentDestinationCreationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentDestinationCreationTest.java deleted file mode 100644 index 4fb283d168..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentDestinationCreationTest.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.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.lang.management.ManagementFactory; -import java.lang.management.ThreadInfo; -import java.lang.management.ThreadMXBean; -import java.util.Vector; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQQueue; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ConcurrentDestinationCreationTest extends org.apache.activemq.TestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(ConcurrentDestinationCreationTest.class); - BrokerService broker; - - @Override - protected void setUp() throws Exception { - broker = createBroker(); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - broker.stop(); - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() + "?jms.watchTopicAdvisories=false&jms.closeTimeout=35000"); - } - - BrokerService createBroker() throws Exception { - BrokerService service = new BrokerService(); - service.setDeleteAllMessagesOnStartup(true); - service.setAdvisorySupport(false); - service.setTransportConnectorURIs(new String[]{"tcp://localhost:0"}); - service.setPersistent(false); - service.setUseJmx(false); - service.start(); - return service; - } - - public void testSendRateWithActivatingConsumers() throws Exception { - - final Vector exceptions = new Vector<>(); - final int jobs = 50; - final int destinationCount = 10; - final CountDownLatch allDone = new CountDownLatch(jobs); - ExecutorService executor = java.util.concurrent.Executors.newCachedThreadPool(); - for (int i = 0; i < jobs; i++) { - if (i % 2 == 0 && i < jobs / 2) { - executor.execute(new Runnable() { - final ConnectionFactory factory = createConnectionFactory(); - - @Override - public void run() { - try { - final Connection connection = factory.createConnection(); - connection.start(); - final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - for (int j = 0; j < jobs * 10; j++) { - final MessageProducer producer = session.createProducer(new ActiveMQQueue("Q." + (j % destinationCount))); - producer.send(session.createMessage()); - } - connection.close(); - allDone.countDown(); - LOG.info("Producers done!"); - } catch (Exception ignored) { - LOG.error("unexpected ", ignored); - exceptions.add(ignored); - } - } - }); - } else { - - executor.execute(new Runnable() { - final ConnectionFactory factory = createConnectionFactory(); - - @Override - public void run() { - try { - final Connection connection = factory.createConnection(); - connection.start(); - final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - for (int j = 0; j < jobs; j++) { - final MessageConsumer consumer = session.createConsumer(new ActiveMQQueue("Q.>")); - consumer.receiveNoWait(); - } - connection.close(); - allDone.countDown(); - LOG.info("Consumers done!"); - } catch (Exception ignored) { - LOG.error("unexpected ", ignored); - exceptions.add(ignored); - } - } - }); - } - } - LOG.info("Waiting for completion"); - executor.shutdown(); - boolean success = allDone.await(30, TimeUnit.SECONDS); - if (!success) { - dumpAllThreads("hung"); - - ThreadMXBean bean = ManagementFactory.getThreadMXBean(); - LOG.info("Supports dead lock detection: " + bean.isSynchronizerUsageSupported()); - long[] threadIds = bean.findDeadlockedThreads(); - if (threadIds != null) { - System.err.println("Dead locked threads...."); - ThreadInfo[] infos = bean.getThreadInfo(threadIds); - - for (ThreadInfo info : infos) { - StackTraceElement[] stack = info.getStackTrace(); - System.err.println(" " + info + ", stack size::" + stack.length); - for (StackTraceElement stackEntry : stack) { - System.err.println(" " + stackEntry); - } - } - } - } - assertTrue("Finished on time", success); - assertTrue("No unexpected exceptions", exceptions.isEmpty()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentProducerDurableConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentProducerDurableConsumerTest.java deleted file mode 100644 index 0df6875297..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentProducerDurableConsumerTest.java +++ /dev/null @@ -1,476 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.jms.TopicSubscriber; -import java.util.ArrayList; -import java.util.Arrays; -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.concurrent.ConcurrentHashMap; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ActiveMQPrefetchPolicy; -import org.apache.activemq.TestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.broker.region.policy.StorePendingDurableSubscriberMessageStoragePolicy; -import org.apache.activemq.command.MessageId; -import org.apache.activemq.util.MessageIdList; -import org.apache.activemq.util.Wait; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@RunWith(value = Parameterized.class) -public class ConcurrentProducerDurableConsumerTest extends TestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(ConcurrentProducerDurableConsumerTest.class); - private final int consumerCount = 5; - BrokerService broker; - protected List connections = Collections.synchronizedList(new ArrayList()); - protected Map consumers = new HashMap<>(); - protected MessageIdList allMessagesList = new MessageIdList(); - private final int messageSize = 1024; - - private final TestSupport.PersistenceAdapterChoice persistenceAdapterChoice; - - @Parameterized.Parameters - public static Collection getTestParameters() { - TestSupport.PersistenceAdapterChoice[] kahaDb = {TestSupport.PersistenceAdapterChoice.KahaDB}; - TestSupport.PersistenceAdapterChoice[] levelDb = {TestSupport.PersistenceAdapterChoice.LevelDB}; - TestSupport.PersistenceAdapterChoice[] mem = {TestSupport.PersistenceAdapterChoice.MEM}; - List choices = new ArrayList<>(); - choices.add(kahaDb); - choices.add(levelDb); - choices.add(mem); - return choices; - } - - public ConcurrentProducerDurableConsumerTest(TestSupport.PersistenceAdapterChoice choice) { - this.persistenceAdapterChoice = choice; - } - - @Test(timeout = 120000) - public void testSendRateWithActivatingConsumers() throws Exception { - final Destination destination = createDestination(); - final ConnectionFactory factory = createConnectionFactory(); - startInactiveConsumers(factory, destination); - - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = createMessageProducer(session, destination); - - // preload the durable consumers - double[] inactiveConsumerStats = produceMessages(destination, 500, 10, session, producer, null); - LOG.info("With inactive consumers: ave: " + inactiveConsumerStats[1] + ", max: " + inactiveConsumerStats[0] + ", multiplier: " + (inactiveConsumerStats[0] / inactiveConsumerStats[1])); - - // periodically start a durable sub that has a backlog - final int consumersToActivate = 5; - final CountDownLatch addConsumerSignal = new CountDownLatch(1); - Executors.newCachedThreadPool(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "ActivateConsumer" + this); - } - }).execute(new Runnable() { - @Override - public void run() { - try { - MessageConsumer consumer = null; - for (int i = 0; i < consumersToActivate; i++) { - LOG.info("Waiting for add signal from producer..."); - addConsumerSignal.await(30, TimeUnit.MINUTES); - TimedMessageListener listener = new TimedMessageListener(); - consumer = createDurableSubscriber(factory.createConnection(), destination, "consumer" + (i + 1)); - LOG.info("Created consumer " + consumer); - consumer.setMessageListener(listener); - consumers.put(consumer, listener); - } - } catch (Exception e) { - LOG.error("failed to start consumer", e); - } - } - }); - - double[] statsWithActive = produceMessages(destination, 500, 10, session, producer, addConsumerSignal); - - LOG.info(" with concurrent activate, ave: " + statsWithActive[1] + ", max: " + statsWithActive[0] + ", multiplier: " + (statsWithActive[0] / statsWithActive[1])); - - while (consumers.size() < consumersToActivate) { - TimeUnit.SECONDS.sleep(2); - } - - long timeToFirstAccumulator = 0; - for (TimedMessageListener listener : consumers.values()) { - long time = listener.getFirstReceipt(); - timeToFirstAccumulator += time; - LOG.info("Time to first " + time); - } - LOG.info("Ave time to first message =" + timeToFirstAccumulator / consumers.size()); - - for (TimedMessageListener listener : consumers.values()) { - LOG.info("Ave batch receipt time: " + listener.waitForReceivedLimit(10000) + " max receipt: " + listener.maxReceiptTime); - } - - //assertTrue("max (" + statsWithActive[0] + ") within reasonable multiplier of ave (" + statsWithActive[1] + ")", - // statsWithActive[0] < 5 * statsWithActive[1]); - - // compare no active to active - LOG.info("Ave send time with active: " + statsWithActive[1] + " as multiplier of ave with none active: " + inactiveConsumerStats[1] + ", multiplier=" + (statsWithActive[1] / inactiveConsumerStats[1])); - - assertTrue("Ave send time with active: " + statsWithActive[1] + " within reasonable multpler of ave with none active: " + inactiveConsumerStats[1] + ", multiplier " + (statsWithActive[1] / inactiveConsumerStats[1]), statsWithActive[1] < 15 * inactiveConsumerStats[1]); - } - - public void x_testSendWithInactiveAndActiveConsumers() throws Exception { - Destination destination = createDestination(); - ConnectionFactory factory = createConnectionFactory(); - startInactiveConsumers(factory, destination); - - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - - final int toSend = 100; - final int numIterations = 5; - - double[] noConsumerStats = produceMessages(destination, toSend, numIterations, session, producer, null); - - startConsumers(factory, destination); - LOG.info("Activated consumer"); - - double[] withConsumerStats = produceMessages(destination, toSend, numIterations, session, producer, null); - - LOG.info("With consumer: " + withConsumerStats[1] + " , with noConsumer: " + noConsumerStats[1] + ", multiplier: " + (withConsumerStats[1] / noConsumerStats[1])); - final int reasonableMultiplier = 15; // not so reasonable but improving - assertTrue("max X times as slow with consumer: " + withConsumerStats[1] + ", with no Consumer: " + noConsumerStats[1] + ", multiplier: " + (withConsumerStats[1] / noConsumerStats[1]), withConsumerStats[1] < noConsumerStats[1] * reasonableMultiplier); - - final int toReceive = toSend * numIterations * consumerCount * 2; - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("count: " + allMessagesList.getMessageCount()); - return toReceive == allMessagesList.getMessageCount(); - } - }, 60 * 1000); - - assertEquals("got all messages", toReceive, allMessagesList.getMessageCount()); - } - - private MessageProducer createMessageProducer(Session session, Destination destination) throws JMSException { - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - return producer; - } - - private void startInactiveConsumers(ConnectionFactory factory, Destination destination) throws Exception { - // create off line consumers - startConsumers(factory, destination); - for (Connection connection : connections) { - connection.close(); - } - connections.clear(); - consumers.clear(); - } - - protected void startConsumers(ConnectionFactory factory, Destination dest) throws Exception { - MessageConsumer consumer; - for (int i = 0; i < consumerCount; i++) { - TimedMessageListener list = new TimedMessageListener(); - consumer = createDurableSubscriber(factory.createConnection(), dest, "consumer" + (i + 1)); - consumer.setMessageListener(list); - consumers.put(consumer, list); - } - } - - protected TopicSubscriber createDurableSubscriber(Connection conn, Destination dest, String name) throws Exception { - conn.setClientID(name); - connections.add(conn); - conn.start(); - - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - final TopicSubscriber consumer = sess.createDurableSubscriber((javax.jms.Topic) dest, name); - - return consumer; - } - - /** - * @return max and ave send time - * @throws Exception - */ - private double[] produceMessages(Destination destination, - final int toSend, - final int numIterations, - Session session, - MessageProducer producer, - CountDownLatch addConsumerSignal) throws Exception { - long start; - long count = 0; - double batchMax = 0, max = 0, sum = 0; - for (int i = 0; i < numIterations; i++) { - start = System.currentTimeMillis(); - for (int j = 0; j < toSend; j++) { - long singleSendstart = System.currentTimeMillis(); - TextMessage msg = createTextMessage(session, "" + j); - // rotate - int priority = ((int) count % 10); - producer.send(msg, DeliveryMode.PERSISTENT, priority, 0); - max = Math.max(max, (System.currentTimeMillis() - singleSendstart)); - if (++count % 500 == 0) { - if (addConsumerSignal != null) { - addConsumerSignal.countDown(); - LOG.info("Signalled add consumer"); - } - } - if (count % 5000 == 0) { - LOG.info("Sent " + count + ", singleSendMax:" + max); - } - - } - long duration = System.currentTimeMillis() - start; - batchMax = Math.max(batchMax, duration); - sum += duration; - LOG.info("Iteration " + i + ", sent " + toSend + ", time: " + duration + ", batchMax:" + batchMax + ", singleSendMax:" + max); - } - - LOG.info("Sent: " + toSend * numIterations + ", batchMax: " + batchMax + " singleSendMax: " + max); - return new double[]{batchMax, sum / numIterations}; - } - - protected TextMessage createTextMessage(Session session, String initText) throws Exception { - TextMessage msg = session.createTextMessage(); - - // Pad message text - if (initText.length() < messageSize) { - char[] data = new char[messageSize - initText.length()]; - Arrays.fill(data, '*'); - String str = new String(data); - msg.setText(initText + str); - - // Do not pad message text - } else { - msg.setText(initText); - } - - return msg; - } - - @Override - @Before - public void setUp() throws Exception { - topic = true; - super.setUp(); - broker = createBroker(); - broker.start(); - } - - @Override - @After - public void tearDown() throws Exception { - for (Iterator iter = connections.iterator(); iter.hasNext(); ) { - Connection conn = iter.next(); - try { - conn.close(); - } catch (Throwable e) { - } - } - broker.stop(); - allMessagesList.flushMessages(); - consumers.clear(); - super.tearDown(); - } - - protected BrokerService createBroker() throws Exception { - BrokerService brokerService = new BrokerService(); - brokerService.setEnableStatistics(false); - brokerService.addConnector("tcp://0.0.0.0:0"); - brokerService.setDeleteAllMessagesOnStartup(true); - - PolicyEntry policy = new PolicyEntry(); - policy.setPrioritizedMessages(true); - policy.setMaxPageSize(500); - - StorePendingDurableSubscriberMessageStoragePolicy durableSubPending = new StorePendingDurableSubscriberMessageStoragePolicy(); - durableSubPending.setImmediatePriorityDispatch(true); - durableSubPending.setUseCache(true); - policy.setPendingDurableSubscriberPolicy(durableSubPending); - - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(policy); - brokerService.setDestinationPolicy(policyMap); - - // if (false) { - // // external mysql works a lot faster - // // - // JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); - // BasicDataSource ds = new BasicDataSource(); - // com.mysql.jdbc.Driver d = new com.mysql.jdbc.Driver(); - // ds.setDriverClassName("com.mysql.jdbc.Driver"); - // ds.setUrl("jdbc:mysql://localhost/activemq?relaxAutoCommit=true"); - // ds.setMaxActive(200); - // ds.setUsername("root"); - // ds.setPassword(""); - // ds.setPoolPreparedStatements(true); - // jdbc.setDataSource(ds); - // brokerService.setPersistenceAdapter(jdbc); - - /* add mysql bits to the pom in the testing dependencies - - mysql - mysql-connector-java - 5.1.10 - test - - - commons-dbcp - commons-dbcp - 1.2.2 - test - - */ - // } else { - setPersistenceAdapter(brokerService, persistenceAdapterChoice); - // } - return brokerService; - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); - ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); - prefetchPolicy.setAll(1); - factory.setPrefetchPolicy(prefetchPolicy); - - factory.setDispatchAsync(true); - return factory; - } - - class TimedMessageListener implements MessageListener { - - final int batchSize = 1000; - CountDownLatch firstReceiptLatch = new CountDownLatch(1); - long mark = System.currentTimeMillis(); - long firstReceipt = 0L; - long receiptAccumulator = 0; - long batchReceiptAccumulator = 0; - long maxReceiptTime = 0; - AtomicLong count = new AtomicLong(0); - Map messageLists = new ConcurrentHashMap<>(new HashMap()); - - @Override - public void onMessage(Message message) { - final long current = System.currentTimeMillis(); - final long duration = current - mark; - receiptAccumulator += duration; - int priority = 0; - try { - priority = message.getJMSPriority(); - } catch (JMSException ignored) { - } - if (!messageLists.containsKey(priority)) { - MessageIdList perPriorityList = new MessageIdList(); - perPriorityList.setParent(allMessagesList); - messageLists.put(priority, perPriorityList); - } - messageLists.get(priority).onMessage(message); - if (count.incrementAndGet() == 1) { - firstReceipt = duration; - firstReceiptLatch.countDown(); - LOG.info("First receipt in " + firstReceipt + "ms"); - } else if (count.get() % batchSize == 0) { - LOG.info("Consumed " + count.get() + " in " + batchReceiptAccumulator + "ms" + ", priority:" + priority); - batchReceiptAccumulator = 0; - } - maxReceiptTime = Math.max(maxReceiptTime, duration); - receiptAccumulator += duration; - batchReceiptAccumulator += duration; - mark = current; - } - - long getMessageCount() { - return count.get(); - } - - long getFirstReceipt() throws Exception { - firstReceiptLatch.await(30, TimeUnit.SECONDS); - return firstReceipt; - } - - public long waitForReceivedLimit(long limit) throws Exception { - final long expiry = System.currentTimeMillis() + 30 * 60 * 1000; - while (count.get() < limit) { - if (System.currentTimeMillis() > expiry) { - throw new RuntimeException("Expired waiting for X messages, " + limit); - } - TimeUnit.SECONDS.sleep(2); - String missing = findFirstMissingMessage(); - if (missing != null) { - LOG.info("first missing = " + missing); - throw new RuntimeException("We have a missing message. " + missing); - } - - } - return receiptAccumulator / (limit / batchSize); - } - - private String findFirstMissingMessage() { - MessageId current = new MessageId(); - for (MessageIdList priorityList : messageLists.values()) { - MessageId previous = null; - for (String id : priorityList.getMessageIds()) { - current.setValue(id); - if (previous == null) { - previous = current.copy(); - } else { - if (current.getProducerSequenceId() - 1 != previous.getProducerSequenceId() && current.getProducerSequenceId() - 10 != previous.getProducerSequenceId()) { - return "Missing next after: " + previous + ", got: " + current; - } else { - previous = current.copy(); - } - } - } - } - return null; - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentProducerQueueConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentProducerQueueConsumerTest.java deleted file mode 100644 index 9631a0c3f4..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConcurrentProducerQueueConsumerTest.java +++ /dev/null @@ -1,417 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - -import junit.framework.Test; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ActiveMQPrefetchPolicy; -import org.apache.activemq.TestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.util.MessageIdList; -import org.apache.activemq.util.Wait; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ConcurrentProducerQueueConsumerTest extends TestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(ConcurrentProducerQueueConsumerTest.class); - - protected List connections = Collections.synchronizedList(new ArrayList()); - protected Map consumers = new HashMap<>(); - protected MessageIdList allMessagesList = new MessageIdList(); - - private BrokerService broker; - private final int consumerCount = 5; - private final int messageSize = 1024; - private final int NUM_MESSAGES = 500; - private final int ITERATIONS = 10; - - private int expectedQueueDeliveries = 0; - - public void initCombosForTestSendRateWithActivatingConsumers() throws Exception { - addCombinationValues("defaultPersistenceAdapter", new Object[]{PersistenceAdapterChoice.KahaDB, PersistenceAdapterChoice.LevelDB, - /* too slow for hudson - PersistenceAdapterChoice.JDBC,*/ - PersistenceAdapterChoice.MEM}); - } - - public void testSendRateWithActivatingConsumers() throws Exception { - final Destination destination = createDestination(); - final ConnectionFactory factory = createConnectionFactory(); - - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = createMessageProducer(session, destination); - - // preload the queue before adding any consumers - double[] noConsumerStats = produceMessages(destination, NUM_MESSAGES, ITERATIONS, session, producer, null); - LOG.info("With no consumers: ave: " + noConsumerStats[1] + ", max: " + - noConsumerStats[0] + ", multiplier: " + (noConsumerStats[0] / noConsumerStats[1])); - expectedQueueDeliveries = NUM_MESSAGES * ITERATIONS; - - // periodically start a queue consumer - final int consumersToActivate = 5; - final CountDownLatch addConsumerSignal = new CountDownLatch(1); - Executors.newCachedThreadPool(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "ActivateConsumer" + this); - } - }).execute(new Runnable() { - @Override - public void run() { - try { - MessageConsumer consumer = null; - for (int i = 0; i < consumersToActivate; i++) { - LOG.info("Waiting for add signal from producer..."); - addConsumerSignal.await(30, TimeUnit.MINUTES); - TimedMessageListener listener = new TimedMessageListener(); - consumer = createConsumer(factory.createConnection(), destination); - LOG.info("Created consumer " + consumer); - consumer.setMessageListener(listener); - consumers.put(consumer, listener); - } - } catch (Exception e) { - LOG.error("failed to start consumer", e); - } - } - }); - - // Collect statistics when there are active consumers. - double[] statsWithActive = produceMessages(destination, NUM_MESSAGES, ITERATIONS, session, producer, addConsumerSignal); - expectedQueueDeliveries += NUM_MESSAGES * ITERATIONS; - - LOG.info(" with concurrent activate, ave: " + statsWithActive[1] + ", max: " + - statsWithActive[0] + ", multiplier: " + (statsWithActive[0] / statsWithActive[1])); - - assertTrue(Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return consumers.size() == consumersToActivate; - } - })); - - long timeToFirstAccumulator = 0; - for (TimedMessageListener listener : consumers.values()) { - long time = listener.getFirstReceipt(); - timeToFirstAccumulator += time; - LOG.info("Time to first " + time); - } - LOG.info("Ave time to first message =" + timeToFirstAccumulator / consumers.size()); - - for (TimedMessageListener listener : consumers.values()) { - LOG.info("Ave batch receipt time: " + listener.waitForReceivedLimit(expectedQueueDeliveries) + - " max receipt: " + listener.maxReceiptTime); - } - - // compare no active to active - LOG.info("Ave send time with active: " + statsWithActive[1] + " as multiplier of ave with none active: " + noConsumerStats[1] + ", multiplier=" + (statsWithActive[1] / noConsumerStats[1])); - - assertTrue("Ave send time with active: " + statsWithActive[1] + " within reasonable multpler of ave with none active: " + noConsumerStats[1] + ", multiplier " + (statsWithActive[1] / noConsumerStats[1]), statsWithActive[1] < 15 * noConsumerStats[1]); - } - - public void x_initCombosForTestSendWithInactiveAndActiveConsumers() throws Exception { - addCombinationValues("defaultPersistenceAdapter", new Object[]{PersistenceAdapterChoice.KahaDB, PersistenceAdapterChoice.LevelDB, - /* too slow for hudson - PersistenceAdapterChoice.JDBC,*/ - PersistenceAdapterChoice.MEM}); - } - - public void x_testSendWithInactiveAndActiveConsumers() throws Exception { - Destination destination = createDestination(); - ConnectionFactory factory = createConnectionFactory(); - - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - - final int toSend = 100; - final int numIterations = 5; - - double[] noConsumerStats = produceMessages(destination, toSend, numIterations, session, producer, null); - - startConsumers(factory, destination); - LOG.info("Activated consumer"); - - double[] withConsumerStats = produceMessages(destination, toSend, numIterations, session, producer, null); - - LOG.info("With consumer: " + withConsumerStats[1] + " , with noConsumer: " + noConsumerStats[1] + ", multiplier: " + (withConsumerStats[1] / noConsumerStats[1])); - final int reasonableMultiplier = 15; // not so reasonable but improving - assertTrue("max X times as slow with consumer: " + withConsumerStats[1] + ", with no Consumer: " + noConsumerStats[1] + ", multiplier: " + (withConsumerStats[1] / noConsumerStats[1]), withConsumerStats[1] < noConsumerStats[1] * reasonableMultiplier); - - final int toReceive = toSend * numIterations * consumerCount * 2; - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("count: " + allMessagesList.getMessageCount()); - return toReceive == allMessagesList.getMessageCount(); - } - }, 60 * 1000); - - assertEquals("got all messages", toReceive, allMessagesList.getMessageCount()); - } - - private MessageProducer createMessageProducer(Session session, Destination destination) throws JMSException { - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - return producer; - } - - protected void startConsumers(ConnectionFactory factory, Destination dest) throws Exception { - MessageConsumer consumer; - for (int i = 0; i < consumerCount; i++) { - TimedMessageListener list = new TimedMessageListener(); - consumer = createConsumer(factory.createConnection(), dest); - consumer.setMessageListener(list); - consumers.put(consumer, list); - } - } - - protected MessageConsumer createConsumer(Connection conn, Destination dest) throws Exception { - connections.add(conn); - conn.start(); - - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageConsumer consumer = sess.createConsumer(dest); - - return consumer; - } - - /** - * @return max and average send time - * @throws Exception - */ - private double[] produceMessages(Destination destination, - final int toSend, - final int numIterations, - Session session, - MessageProducer producer, - CountDownLatch addConsumerSignal) throws Exception { - long start; - long count = 0; - double batchMax = 0, max = 0, sum = 0; - - for (int i = 0; i < numIterations; i++) { - start = System.currentTimeMillis(); - for (int j = 0; j < toSend; j++) { - long singleSendstart = System.currentTimeMillis(); - TextMessage msg = createTextMessage(session, "" + j); - // rotate - int priority = ((int) count % 10); - producer.send(msg, DeliveryMode.PERSISTENT, priority, 0); - max = Math.max(max, (System.currentTimeMillis() - singleSendstart)); - if (++count % 500 == 0) { - if (addConsumerSignal != null) { - addConsumerSignal.countDown(); - LOG.info("Signalled add consumer"); - } - } - if (count % 5000 == 0) { - LOG.info("Sent " + count + ", singleSendMax:" + max); - } - - } - long duration = System.currentTimeMillis() - start; - batchMax = Math.max(batchMax, duration); - sum += duration; - LOG.info("Iteration " + i + ", sent " + toSend + ", time: " + duration + ", batchMax:" + batchMax + ", singleSendMax:" + max); - } - - LOG.info("Sent: " + toSend * numIterations + ", batchMax: " + batchMax + " singleSendMax: " + max); - return new double[]{batchMax, sum / numIterations}; - } - - protected TextMessage createTextMessage(Session session, String initText) throws Exception { - TextMessage msg = session.createTextMessage(); - - // Pad message text - if (initText.length() < messageSize) { - char[] data = new char[messageSize - initText.length()]; - Arrays.fill(data, '*'); - String str = new String(data); - msg.setText(initText + str); - - // Do not pad message text - } else { - msg.setText(initText); - } - - return msg; - } - - @Override - protected void setUp() throws Exception { - topic = false; - super.setUp(); - broker = createBroker(); - broker.start(); - } - - @Override - protected void tearDown() throws Exception { - for (Iterator iter = connections.iterator(); iter.hasNext(); ) { - Connection conn = iter.next(); - try { - conn.close(); - } catch (Throwable e) { - } - } - broker.stop(); - allMessagesList.flushMessages(); - consumers.clear(); - super.tearDown(); - } - - protected BrokerService createBroker() throws Exception { - BrokerService brokerService = new BrokerService(); - brokerService.setEnableStatistics(false); - brokerService.addConnector("tcp://0.0.0.0:0"); - brokerService.setDeleteAllMessagesOnStartup(true); - - PolicyEntry policy = new PolicyEntry(); - policy.setPrioritizedMessages(true); - policy.setMaxPageSize(500); - - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(policy); - brokerService.setDestinationPolicy(policyMap); - setDefaultPersistenceAdapter(brokerService); - - return brokerService; - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString()); - ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); - prefetchPolicy.setAll(1); - factory.setPrefetchPolicy(prefetchPolicy); - - factory.setDispatchAsync(true); - return factory; - } - - public static Test suite() { - return suite(ConcurrentProducerQueueConsumerTest.class); - } - - static class TimedMessageListener implements MessageListener { - - static final AtomicLong count = new AtomicLong(0); - - final int batchSize = 1000; - final CountDownLatch firstReceiptLatch = new CountDownLatch(1); - - long mark = System.currentTimeMillis(); - long firstReceipt = 0L; - long receiptAccumulator = 0; - long batchReceiptAccumulator = 0; - long maxReceiptTime = 0; - - final Map messageLists = new ConcurrentHashMap<>(new HashMap()); - - @Override - public void onMessage(Message message) { - final long current = System.currentTimeMillis(); - final long duration = current - mark; - receiptAccumulator += duration; - int priority = 0; - - try { - priority = message.getJMSPriority(); - } catch (JMSException ignored) { - } - - if (!messageLists.containsKey(priority)) { - messageLists.put(priority, new MessageIdList()); - } - messageLists.get(priority).onMessage(message); - - if (count.incrementAndGet() == 1) { - firstReceipt = duration; - firstReceiptLatch.countDown(); - LOG.info("First receipt in " + firstReceipt + "ms"); - } else if (count.get() % batchSize == 0) { - LOG.info("Consumed " + count.get() + " in " + batchReceiptAccumulator + "ms" + ", priority:" + priority); - batchReceiptAccumulator = 0; - } - - maxReceiptTime = Math.max(maxReceiptTime, duration); - receiptAccumulator += duration; - batchReceiptAccumulator += duration; - mark = current; - } - - long getMessageCount() { - return count.get(); - } - - long getFirstReceipt() throws Exception { - firstReceiptLatch.await(30, TimeUnit.SECONDS); - return firstReceipt; - } - - public long waitForReceivedLimit(long limit) throws Exception { - final long expiry = System.currentTimeMillis() + 30 * 60 * 1000; - while (count.get() < limit) { - if (System.currentTimeMillis() > expiry) { - throw new RuntimeException("Expired waiting for X messages, " + limit); - } - TimeUnit.SECONDS.sleep(2); - String missing = findFirstMissingMessage(); - if (missing != null) { - LOG.info("first missing = " + missing); - throw new RuntimeException("We have a missing message. " + missing); - } - - } - return receiptAccumulator / (limit / batchSize); - } - - private String findFirstMissingMessage() { - return null; - } - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeQueuePrefetchTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeQueuePrefetchTest.java deleted file mode 100644 index 85efbc2caf..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeQueuePrefetchTest.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.activemq.usecases; - -import javax.jms.JMSException; -import javax.jms.Message; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ConsumeQueuePrefetchTest extends ConsumeTopicPrefetchTest { - - private static final Logger LOG = LoggerFactory.getLogger(ConsumeQueuePrefetchTest.class); - - @Override - protected void setUp() throws Exception { - topic = false; - super.setUp(); - } - - public void testInflightWithConsumerPerMessage() throws JMSException { - makeMessages(prefetchSize); - - LOG.info("About to send and receive: " + prefetchSize + " on destination: " + destination + " of type: " + destination.getClass().getName()); - - for (int i = 0; i < prefetchSize; i++) { - Message message = session.createTextMessage(messageTexts[i]); - producer.send(message); - } - - validateConsumerPrefetch(this.getSubject(), prefetchSize); - - // new consumer per 20 messages - for (int i = 0; i < prefetchSize; i += 20) { - consumer.close(); - consumer = session.createConsumer(destination); - validateConsumerPrefetch(this.getSubject(), prefetchSize - i); - for (int j = 0; j < 20; j++) { - Message message = consumeMessge(i + j); - message.acknowledge(); - } - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeTopicPrefetchTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeTopicPrefetchTest.java deleted file mode 100644 index 04c858e768..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeTopicPrefetchTest.java +++ /dev/null @@ -1,155 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.TextMessage; -import java.util.LinkedList; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.broker.BrokerRegistry; -import org.apache.activemq.broker.region.DestinationStatistics; -import org.apache.activemq.broker.region.RegionBroker; -import org.apache.activemq.util.Wait; -import org.apache.activemq.util.Wait.Condition; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class ConsumeTopicPrefetchTest extends ProducerConsumerTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(ConsumeTopicPrefetchTest.class); - - protected int prefetchSize = 100; - protected String[] messageTexts; - protected long consumerTimeout = 10000L; - - public void testSendPrefetchSize() throws JMSException { - testWithMessageCount(prefetchSize); - } - - public void testSendDoublePrefetchSize() throws JMSException { - testWithMessageCount(prefetchSize * 2); - } - - public void testSendPrefetchSizePlusOne() throws JMSException { - testWithMessageCount(prefetchSize + 1); - } - - protected void testWithMessageCount(int messageCount) throws JMSException { - makeMessages(messageCount); - - LOG.info("About to send and receive: " + messageCount + " on destination: " + destination + " of type: " + destination.getClass().getName()); - - for (int i = 0; i < messageCount; i++) { - Message message = session.createTextMessage(messageTexts[i]); - producer.send(message); - } - - validateConsumerPrefetch(this.getSubject(), prefetchSize); - - LinkedList consumed = new LinkedList<>(); - // lets consume them in two fetch batches - int batchSize = messageCount / 2; - for (int i = 0; i < batchSize; i++) { - consumed.add(consumeMessge(i)); - } - - // delayed delivered ack a .5 prefetch - validateConsumerPrefetchGreaterOrEqual(this.getSubject(), (long) Math.min(messageCount, 1.5 * prefetchSize)); - - for (int i = 0; i < batchSize; i++) { - consumed.remove().acknowledge(); - } - - // second batch to consume the rest - for (int i = batchSize; i < messageCount; i++) { - consumeMessge(i).acknowledge(); - } - validateConsumerPrefetch(this.getSubject(), 0); - } - - @Override - protected Connection createConnection() throws Exception { - ActiveMQConnection connection = (ActiveMQConnection) super.createConnection(); - connection.getPrefetchPolicy().setQueuePrefetch(prefetchSize); - connection.getPrefetchPolicy().setTopicPrefetch(prefetchSize); - return connection; - } - - protected TextMessage consumeMessge(int i) throws JMSException { - Message message = consumer.receive(consumerTimeout); - assertTrue("Should have received a message by now for message: " + i, message != null); - assertTrue("Should be a TextMessage: " + message, message instanceof TextMessage); - TextMessage textMessage = (TextMessage) message; - assertEquals("Message content", messageTexts[i], textMessage.getText()); - return textMessage; - } - - protected void makeMessages(int messageCount) { - messageTexts = new String[messageCount]; - for (int i = 0; i < messageCount; i++) { - messageTexts[i] = "Message for test: + " + getName() + " = " + i; - } - } - - private void validateConsumerPrefetchGreaterOrEqual(String subject, long min) throws JMSException { - doValidateConsumerPrefetch(subject, min, true); - } - - protected void validateConsumerPrefetch(String subject, final long expectedCount) throws JMSException { - doValidateConsumerPrefetch(subject, expectedCount, false); - } - - protected void doValidateConsumerPrefetch(String destination, - final long expectedCount, - final boolean greaterOrEqual) throws JMSException { - RegionBroker regionBroker = (RegionBroker) BrokerRegistry.getInstance().lookup("localhost").getRegionBroker(); - for (org.apache.activemq.broker.region.Destination dest : regionBroker.getTopicRegion().getDestinationMap().values()) { - final org.apache.activemq.broker.region.Destination target = dest; - if (dest.getName().equals(destination)) { - try { - Wait.waitFor(new Condition() { - @Override - public boolean isSatisified() throws Exception { - DestinationStatistics stats = target.getDestinationStatistics(); - LOG.info("inflight for : " + target.getName() + ": " + stats.getInflight().getCount()); - if (greaterOrEqual) { - return stats.getInflight().getCount() >= expectedCount; - } else { - return stats.getInflight().getCount() == expectedCount; - } - } - }); - } catch (Exception e) { - throw new JMSException(e.toString()); - } - DestinationStatistics stats = dest.getDestinationStatistics(); - LOG.info("inflight for : " + dest.getName() + ": " + stats.getInflight().getCount()); - if (greaterOrEqual) { - assertTrue("inflight for: " + dest.getName() + ": " + stats.getInflight().getCount() + " > " + stats.getInflight().getCount(), stats.getInflight().getCount() >= expectedCount); - } else { - assertEquals("inflight for: " + dest.getName() + ": " + stats.getInflight().getCount() + " matches", expectedCount, stats.getInflight().getCount()); - } - } - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeUncompressedCompressedMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeUncompressedCompressedMessageTest.java deleted file mode 100644 index 5404d7ee0b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ConsumeUncompressedCompressedMessageTest.java +++ /dev/null @@ -1,188 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.usecases; - -import javax.jms.JMSException; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; -import javax.management.openmbean.CompositeData; -import java.net.URI; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.broker.jmx.QueueViewMBean; -import org.apache.activemq.command.ActiveMQMessage; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -public class ConsumeUncompressedCompressedMessageTest { - - private static final Logger LOG = LoggerFactory.getLogger(ConsumeUncompressedCompressedMessageTest.class); - - private BrokerService broker; - private URI tcpUri; - - ActiveMQConnectionFactory factory; - ActiveMQConnection connection; - Session session; - Queue queue; - - @Before - public void setUp() throws Exception { - broker = createBroker(); - broker.start(); - broker.waitUntilStarted(); - - factory = new ActiveMQConnectionFactory(tcpUri); - factory.setUseCompression(true); - - connection = (ActiveMQConnection) factory.createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - queue = session.createQueue("CompressionTestQueue"); - } - - @After - public void tearDown() throws Exception { - - if (connection != null) { - connection.close(); - } - - broker.stop(); - broker.waitUntilStopped(); - } - - protected BrokerService createBroker() throws Exception { - return createBroker(true); - } - - protected BrokerService createBroker(boolean delete) throws Exception { - BrokerService answer = new BrokerService(); - answer.setPersistent(false); - answer.setDeleteAllMessagesOnStartup(true); - answer.setSchedulerSupport(false); - answer.setUseJmx(true); - TransportConnector connector = answer.addConnector("tcp://localhost:0"); - tcpUri = connector.getConnectUri(); - return answer; - } - - @Test - public void testBrowseAndReceiveCompressedMessages() throws Exception { - - assertTrue(connection.isUseCompression()); - - createProducerAndSendMessages(1); - - QueueViewMBean queueView = getProxyToQueueViewMBean(); - - assertNotNull(queueView); - - CompositeData[] compdatalist = queueView.browse(); - if (compdatalist.length == 0) { - fail("There is no message in the queue:"); - } - - CompositeData cdata = compdatalist[0]; - - assertComplexData(0, cdata, "Text", "Test Text Message: " + 0); - - assertMessageAreCorrect(1); - } - - @Test - public void testReceiveAndResendWithCompressionOff() throws Exception { - - assertTrue(connection.isUseCompression()); - - createProducerAndSendMessages(1); - - MessageConsumer consumer = session.createConsumer(queue); - TextMessage message = (TextMessage) consumer.receive(5000); - - assertTrue(((ActiveMQMessage) message).isCompressed()); - - LOG.debug("Received Message with Text = " + message.getText()); - - connection.setUseCompression(false); - - MessageProducer producer = session.createProducer(queue); - producer.send(message); - producer.close(); - - message = (TextMessage) consumer.receive(5000); - - LOG.debug("Received Message with Text = " + message.getText()); - } - - protected void assertComplexData(int messageIndex, CompositeData cdata, String name, Object expected) { - Object value = cdata.get(name); - assertEquals("Message " + messageIndex + " CData field: " + name, expected, value); - } - - private void createProducerAndSendMessages(int numToSend) throws Exception { - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(queue); - for (int i = 0; i < numToSend; i++) { - TextMessage message = session.createTextMessage("Test Text Message: " + i); - if (i != 0 && i % 10000 == 0) { - LOG.info("sent: " + i); - } - producer.send(message); - } - producer.close(); - } - - private QueueViewMBean getProxyToQueueViewMBean() throws MalformedObjectNameException, JMSException { - ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq" + ":destinationType=Queue,destinationName=" + queue.getQueueName() + ",type=Broker,brokerName=localhost"); - QueueViewMBean proxy = (QueueViewMBean) broker.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); - return proxy; - } - - private void assertMessageAreCorrect(int numToReceive) throws Exception { - MessageConsumer consumer = session.createConsumer(queue); - - try { - - for (int i = 0; i < numToReceive; ++i) { - TextMessage message = (TextMessage) consumer.receive(5000); - assertNotNull(message); - assertEquals("Test Text Message: " + i, message.getText()); - } - - } finally { - consumer.close(); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CreateLotsOfTemporaryQueuesTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CreateLotsOfTemporaryQueuesTest.java deleted file mode 100644 index c259759591..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CreateLotsOfTemporaryQueuesTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Session; -import javax.jms.TemporaryQueue; - -import junit.framework.Test; -import junit.framework.TestSuite; - -import junit.textui.TestRunner; -import org.apache.activemq.EmbeddedBrokerAndConnectionTestSupport; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class CreateLotsOfTemporaryQueuesTest extends EmbeddedBrokerAndConnectionTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(CreateLotsOfTemporaryQueuesTest.class); - - private static int numberToCreate = 500; - private static long sleep = 20; - - public static void main(String[] args) { - configure(args); - TestRunner.run(suite()); - } - - public static Test suite() { - return new TestSuite(CreateLotsOfTemporaryQueuesTest.class); - } - - public void testCreateLotsOfTemporaryQueues() throws Exception { - LOG.info("Creating " + numberToCreate + " temporary queue(s)"); - - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - for (int i = 0; i < numberToCreate; i++) { - if (i % 1000 == 0) { - LOG.info("attempt " + i); - } - TemporaryQueue temporaryQueue = session.createTemporaryQueue(); - temporaryQueue.delete(); - Thread.sleep(sleep); - } - LOG.info("Created " + numberToCreate + " temporary queue(s)"); - } - - public static void configure(String[] args) { - if (args.length > 0) { - numberToCreate = Integer.parseInt(args[0]); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CreateTemporaryQueueBeforeStartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CreateTemporaryQueueBeforeStartTest.java deleted file mode 100644 index b35781caa2..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/CreateTemporaryQueueBeforeStartTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Queue; -import javax.jms.QueueConnection; -import javax.jms.QueueSession; -import javax.jms.Session; -import javax.jms.Topic; -import java.util.concurrent.atomic.AtomicInteger; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; - -/** - * @author Peter Henning - */ -public class CreateTemporaryQueueBeforeStartTest extends TestCase { - - private final String bindAddress = "tcp://localhost:0"; - private String connectionUri; - private Connection connection; - private BrokerService broker = new BrokerService(); - - public void testCreateTemporaryQueue() throws Exception { - connection = createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createTemporaryQueue(); - assertTrue("No queue created!", queue != null); - Topic topic = session.createTemporaryTopic(); - assertTrue("No topic created!", topic != null); - } - - public void testTryToReproduceNullPointerBug() throws Exception { - String url = connectionUri; - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url); - QueueConnection queueConnection = factory.createQueueConnection(); - this.connection = queueConnection; - QueueSession session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); - session.createSender(null); // Unidentified - Queue receiverQueue = session.createTemporaryQueue(); - session.createReceiver(receiverQueue); - queueConnection.start(); - } - - public void testTemporaryQueueConsumer() throws Exception { - final int number = 20; - final AtomicInteger count = new AtomicInteger(0); - for (int i = 0; i < number; i++) { - Thread thread = new Thread(new Runnable() { - @Override - public void run() { - try { - QueueConnection connection = createConnection(); - QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); - Queue queue = session.createTemporaryQueue(); - session.createReceiver(queue); - connection.start(); - - if (count.incrementAndGet() >= number) { - synchronized (count) { - count.notify(); - } - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - }); - thread.start(); - } - int maxWaitTime = 20000; - synchronized (count) { - long waitTime = maxWaitTime; - long start = System.currentTimeMillis(); - while (count.get() < number) { - if (waitTime <= 0) { - break; - } else { - count.wait(waitTime); - waitTime = maxWaitTime - (System.currentTimeMillis() - start); - } - } - } - assertTrue("Unexpected count: " + count, count.get() == number); - } - - protected QueueConnection createConnection() throws Exception { - ActiveMQConnectionFactory factory = createConnectionFactory(); - return factory.createQueueConnection(); - } - - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(connectionUri); - } - - @Override - protected void setUp() throws Exception { - broker.setUseJmx(false); - broker.setPersistent(false); - connectionUri = broker.addConnector(bindAddress).getPublishableConnectString(); - broker.start(); - broker.waitUntilStarted(); - - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - broker.stop(); - super.tearDown(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DiscriminatingConsumerLoadTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DiscriminatingConsumerLoadTest.java deleted file mode 100644 index f7a54bf785..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DiscriminatingConsumerLoadTest.java +++ /dev/null @@ -1,306 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; -import javax.jms.TextMessage; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; - -/** - * Test case intended to demonstrate delivery interruption to queue consumers when a JMS selector leaves some messages - * on the queue (due to use of a JMS Selector) - * - * testNonDiscriminatingConsumer() demonstrates proper functionality for consumers that don't use a selector to qualify - * their input. - * - * testDiscriminatingConsumer() demonstrates the failure condition in which delivery to the consumer eventually halts. - * - * The expected behavior is for the delivery to the client to be maintained regardless of the depth of the queue, - * particularly when the messages in the queue do not meet the selector criteria of the client. - * - * https://issues.apache.org/activemq/browse/AMQ-2217 - */ -public class DiscriminatingConsumerLoadTest extends TestSupport { - - private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(DiscriminatingConsumerLoadTest.class); - - private Connection producerConnection; - private Connection consumerConnection; - - public static final String JMSTYPE_EATME = "DiscriminatingLoadClient.EatMe"; - public static final String JMSTYPE_IGNOREME = "DiscriminatingLoadClient.IgnoreMe"; - - private final int testSize = 5000; // setting this to a small number will pass all tests - - BrokerService broker; - - @Override - protected void setUp() throws Exception { - broker = new BrokerService(); - broker.setPersistent(false); - - // workaround is to ensure sufficient dispatch buffer for the destination - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultPolicy = new PolicyEntry(); - defaultPolicy.setMaxPageSize(testSize); - policyMap.setDefaultEntry(defaultPolicy); - broker.setDestinationPolicy(policyMap); - broker.start(); - - super.setUp(); - this.producerConnection = this.createConnection(); - this.consumerConnection = this.createConnection(); - } - - /** - * @see junit.framework.TestCase#tearDown() - */ - @Override - protected void tearDown() throws Exception { - if (producerConnection != null) { - producerConnection.close(); - producerConnection = null; - } - if (consumerConnection != null) { - consumerConnection.close(); - consumerConnection = null; - } - super.tearDown(); - broker.stop(); - } - - /** - * Test to check if a single consumer with no JMS selector will receive all intended messages - * - * @throws java.lang.Exception - */ - public void testNonDiscriminatingConsumer() throws Exception { - - consumerConnection = createConnection(); - consumerConnection.start(); - LOG.info("consumerConnection = " + consumerConnection); - - try { - Thread.sleep(1000); - } catch (Exception e) { - } - - // here we pass in null for the JMS selector - Consumer consumer = new Consumer(consumerConnection, null); - Thread consumerThread = new Thread(consumer); - - consumerThread.start(); - - producerConnection = createConnection(); - producerConnection.start(); - LOG.info("producerConnection = " + producerConnection); - - try { - Thread.sleep(3000); - } catch (Exception e) { - } - - Producer producer = new Producer(producerConnection); - Thread producerThread = new Thread(producer); - producerThread.start(); - - // now that everything is running, let's wait for the consumer thread to finish ... - consumerThread.join(); - producer.stop = true; - - if (consumer.getCount() == testSize) - LOG.info("test complete .... all messsages consumed!!"); - else - LOG.info("test failed .... Sent " + (testSize / 1) + " messages intended to be consumed ( " + testSize + " total), but only consumed " + consumer.getCount()); - - assertTrue("Sent " + testSize + " messages intended to be consumed, but only consumed " + consumer.getCount(), (consumer.getCount() == testSize)); - assertFalse("Delivery of messages to consumer was halted during this test", consumer.deliveryHalted()); - } - - /** - * Test to check if a single consumer with a JMS selector will receive all intended messages - * - * @throws java.lang.Exception - */ - public void testDiscriminatingConsumer() throws Exception { - - consumerConnection = createConnection(); - consumerConnection.start(); - LOG.info("consumerConnection = " + consumerConnection); - - try { - Thread.sleep(1000); - } catch (Exception e) { - } - - // here we pass the JMS selector we intend to consume - Consumer consumer = new Consumer(consumerConnection, JMSTYPE_EATME); - Thread consumerThread = new Thread(consumer); - - consumerThread.start(); - - producerConnection = createConnection(); - producerConnection.start(); - LOG.info("producerConnection = " + producerConnection); - - try { - Thread.sleep(3000); - } catch (Exception e) { - } - - Producer producer = new Producer(producerConnection); - Thread producerThread = new Thread(producer); - producerThread.start(); - - // now that everything is running, let's wait for the consumer thread to finish ... - consumerThread.join(); - producer.stop = true; - - if (consumer.getCount() == (testSize / 2)) { - LOG.info("test complete .... all messsages consumed!!"); - } else { - LOG.info("test failed .... Sent " + testSize + " original messages, only half of which (" + (testSize / 2) + ") were intended to be consumed: consumer paused at: " + consumer.getCount()); - // System.out.println("test failed .... Sent " + testSize + " original messages, only half of which (" + - // (testSize / 2) + - // ") were intended to be consumed: consumer paused at: " + consumer.getCount()); - - } - - assertTrue("Sent " + testSize + " original messages, only half of which (" + (testSize / 2) + ") were intended to be consumed: consumer paused at: " + consumer.getCount(), (consumer.getCount() == (testSize / 2))); - assertTrue("Delivery of messages to consumer was halted during this test as it only wants half", consumer.deliveryHalted()); - } - - /** - * Helper class that will publish 2 * testSize messages. The messages will be distributed evenly between the - * following two JMS types: - * - * @see JMSTYPE_INTENDED_FOR_CONSUMPTION - * @see JMSTYPE_NOT_INTENDED_FOR_CONSUMPTION - */ - private class Producer extends Thread { - - private int counterSent = 0; - private Connection connection = null; - public boolean stop = false; - - public Producer(Connection connection) { - this.connection = connection; - } - - @Override - public void run() { - try { - final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Queue queue = session.createQueue("test"); - - // wait for 10 seconds to allow consumer.receive to be run - // first - Thread.sleep(10000); - MessageProducer producer = session.createProducer(queue); - - while (!stop && (counterSent < testSize)) { - // first send a message intended to be consumed .... - TextMessage message = session.createTextMessage("*** Ill ....... Ini ***"); // alma mater ... - message.setJMSType(JMSTYPE_EATME); - // LOG.info("sending .... JMSType = " + message.getJMSType()); - producer.send(message, DeliveryMode.NON_PERSISTENT, 0, 1800000); - - counterSent++; - - // now send a message intended to be consumed by some other consumer in the the future - // ... we expect these messages to accrue in the queue - message = session.createTextMessage("*** Ill ....... Ini ***"); // alma mater ... - message.setJMSType(JMSTYPE_IGNOREME); - // LOG.info("sending .... JMSType = " + message.getJMSType()); - producer.send(message, DeliveryMode.NON_PERSISTENT, 0, 1800000); - - counterSent++; - } - - session.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - LOG.info("producer thread complete ... " + counterSent + " messages sent to the queue"); - } - } - - /** - * Helper class that will consume messages from the queue based on the supplied JMS selector. Thread will stop after - * the first receive(..) timeout, or once all expected messages have been received (see testSize). If the thread - * stops due to a timeout, it is experiencing the delivery pause that is symptomatic of a bug in the broker. - */ - private class Consumer extends Thread { - - protected int counterReceived = 0; - private String jmsSelector = null; - private boolean deliveryHalted = false; - - public Consumer(Connection connection, String jmsSelector) { - this.jmsSelector = jmsSelector; - } - - @Override - public void run() { - try { - Session session = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - final Queue queue = session.createQueue("test"); - MessageConsumer consumer = null; - if (null != this.jmsSelector) { - consumer = session.createConsumer(queue, "JMSType='" + this.jmsSelector + "'"); - } else { - consumer = session.createConsumer(queue); - } - - while (!deliveryHalted && (counterReceived < testSize)) { - TextMessage result = (TextMessage) consumer.receive(30000); - if (result != null) { - counterReceived++; - // System.out.println("consuming .... JMSType = " + result.getJMSType() + " received = " + - // counterReceived); - LOG.info("consuming .... JMSType = " + result.getJMSType() + " received = " + counterReceived); - } else { - LOG.info("consuming .... timeout while waiting for a message ... broker must have stopped delivery ... received = " + counterReceived); - deliveryHalted = true; - } - } - session.close(); - } catch (Exception e) { - e.printStackTrace(); - } - - } - - public int getCount() { - return this.counterReceived; - } - - public boolean deliveryHalted() { - return this.deliveryHalted; - } - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DispatchMultipleConsumersTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DispatchMultipleConsumersTest.java deleted file mode 100644 index 2dce7f6384..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DispatchMultipleConsumersTest.java +++ /dev/null @@ -1,232 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicInteger; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQQueue; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Rajani Chennamaneni - */ -public class DispatchMultipleConsumersTest extends TestCase { - - private final static Logger logger = LoggerFactory.getLogger(DispatchMultipleConsumersTest.class); - BrokerService broker; - Destination dest; - String destinationName = "TEST.Q"; - String msgStr = "Test text message"; - int messagesPerThread = 20; - int producerThreads = 50; - int consumerCount = 2; - AtomicInteger sentCount; - AtomicInteger consumedCount; - CountDownLatch producerLatch; - CountDownLatch consumerLatch; - String brokerURL; - String userName = ""; - String password = ""; - - @Override - protected void setUp() throws Exception { - super.setUp(); - broker = new BrokerService(); - broker.setPersistent(true); - broker.setUseJmx(true); - broker.deleteAllMessages(); - broker.addConnector("tcp://localhost:0"); - broker.start(); - broker.waitUntilStarted(); - dest = new ActiveMQQueue(destinationName); - resetCounters(); - brokerURL = broker.getTransportConnectors().get(0).getPublishableConnectString(); - } - - @Override - protected void tearDown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - super.tearDown(); - } - - private void resetCounters() { - sentCount = new AtomicInteger(0); - consumedCount = new AtomicInteger(0); - producerLatch = new CountDownLatch(producerThreads); - consumerLatch = new CountDownLatch(consumerCount); - } - - public void testDispatch1() { - for (int i = 1; i <= 5; i++) { - resetCounters(); - dispatch(); - assertEquals("Incorrect messages in Iteration " + i, sentCount.get(), consumedCount.get()); - } - } - - private void dispatch() { - startConsumers(); - startProducers(); - try { - producerLatch.await(); - consumerLatch.await(); - } catch (InterruptedException e) { - fail("test interrupted!"); - } - } - - private void startConsumers() { - ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory(userName, password, brokerURL); - Connection conn; - try { - conn = connFactory.createConnection(); - conn.start(); - for (int i = 0; i < consumerCount; i++) { - new ConsumerThread(conn, "ConsumerThread" + i); - } - } catch (JMSException e) { - logger.error("Failed to start consumers", e); - } - } - - private void startProducers() { - ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory(userName, password, brokerURL); - for (int i = 0; i < producerThreads; i++) { - new ProducerThread(connFactory, messagesPerThread, "ProducerThread" + i); - } - } - - private class ConsumerThread extends Thread { - - Session session; - MessageConsumer consumer; - - public ConsumerThread(Connection conn, String name) { - super(); - this.setName(name); - logger.trace("Created new consumer thread:" + name); - try { - session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session.createConsumer(dest); - start(); - } catch (JMSException e) { - logger.error("Failed to start consumer thread:" + name, e); - } - } - - @Override - public void run() { - int msgCount = 0; - int nullCount = 0; - while (true) { - try { - Message msg = consumer.receive(1000); - if (msg == null) { - if (producerLatch.getCount() > 0) { - continue; - } - nullCount++; - if (nullCount > 10) { - //assume that we are not getting any more messages - break; - } else { - continue; - } - } else { - nullCount = 0; - } - Thread.sleep(100); - if (logger.isTraceEnabled()) { - logger.trace("Message received:" + msg.getJMSMessageID()); - } - msgCount++; - } catch (JMSException e) { - logger.error("Failed to consume:", e); - } catch (InterruptedException e) { - logger.error("Interrupted!", e); - } - } - try { - consumer.close(); - } catch (JMSException e) { - logger.error("Failed to close consumer " + getName(), e); - } - consumedCount.addAndGet(msgCount); - consumerLatch.countDown(); - logger.trace("Consumed " + msgCount + " messages using thread " + getName()); - } - } - - private class ProducerThread extends Thread { - - int count; - Connection conn; - Session session; - MessageProducer producer; - - public ProducerThread(ActiveMQConnectionFactory connFactory, int count, String name) { - super(); - this.count = count; - this.setName(name); - logger.trace("Created new producer thread:" + name); - try { - conn = connFactory.createConnection(); - conn.start(); - session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(dest); - start(); - } catch (JMSException e) { - logger.error("Failed to start producer thread:" + name, e); - } - } - - @Override - public void run() { - int i = 0; - try { - for (; i < count; i++) { - producer.send(session.createTextMessage(msgStr)); - Thread.sleep(500); - } - conn.close(); - } catch (JMSException e) { - logger.error(e.getMessage(), e); - } catch (InterruptedException e) { - logger.error("Interrupted!", e); - } - sentCount.addAndGet(i); - producerLatch.countDown(); - if (logger.isTraceEnabled()) { - logger.trace("Sent " + i + " messages from thread " + getName()); - } - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableConsumerCloseAndReconnectTcpTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableConsumerCloseAndReconnectTcpTest.java deleted file mode 100644 index afd6396b3d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableConsumerCloseAndReconnectTcpTest.java +++ /dev/null @@ -1,212 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.ExceptionListener; -import javax.jms.JMSException; -import javax.net.SocketFactory; -import java.io.IOException; -import java.net.InetAddress; -import java.net.Socket; -import java.net.UnknownHostException; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.transport.TransportFactory; -import org.apache.activemq.transport.TransportListener; -import org.apache.activemq.transport.tcp.TcpTransportFactory; -import org.apache.activemq.util.URISupport; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DurableConsumerCloseAndReconnectTcpTest extends DurableConsumerCloseAndReconnectTest implements ExceptionListener, TransportListener { - - private static final Logger LOG = LoggerFactory.getLogger(DurableConsumerCloseAndReconnectTcpTest.class); - - private BrokerService broker; - private TransportConnector connector; - - private CountDownLatch gotException = new CountDownLatch(1); - - private Exception reconnectException; - - private boolean reconnectInExceptionListener; - - private boolean reconnectInTransportListener; - - @Override - public void setUp() throws Exception { - broker = new BrokerService(); - // let the client initiate the inactivity timeout - connector = broker.addConnector("tcp://localhost:0?transport.useInactivityMonitor=false"); - broker.setPersistent(false); - broker.start(); - broker.waitUntilStarted(); - - class SlowCloseSocketTcpTransportFactory extends TcpTransportFactory { - - class SlowCloseSocketFactory extends SocketFactory { - - class SlowCloseSocket extends Socket { - - public SlowCloseSocket(String host, int port) throws IOException { - super(host, port); - } - - public SlowCloseSocket(InetAddress host, int port) throws IOException { - super(host, port); - } - - public SlowCloseSocket(String host, int port, InetAddress localHost, int localPort) throws IOException { - super(host, port, localHost, localPort); - } - - public SlowCloseSocket(InetAddress address, - int port, - InetAddress localAddress, - int localPort) throws IOException { - super(address, port, localAddress, localPort); - } - - @Override - public synchronized void close() throws IOException { - LOG.info("delaying close"); - try { - TimeUnit.MILLISECONDS.sleep(500); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - super.close(); - } - - } - - @Override - public Socket createSocket(String host, int port) throws IOException, UnknownHostException { - return new SlowCloseSocket(host, port); - } - - @Override - public Socket createSocket(InetAddress host, int port) throws IOException { - return new SlowCloseSocket(host, port); - } - - @Override - public Socket createSocket(String host, - int port, - InetAddress localHost, - int localPort) throws IOException, UnknownHostException { - return new SlowCloseSocket(host, port, localHost, localPort); - } - - @Override - public Socket createSocket(InetAddress address, - int port, - InetAddress localAddress, - int localPort) throws IOException { - return new SlowCloseSocket(address, port, localAddress, localPort); - } - - } - - @Override - protected SocketFactory createSocketFactory() throws IOException { - return new SlowCloseSocketFactory(); - } - - } - - TransportFactory.registerTransportFactory("tcp", new SlowCloseSocketTcpTransportFactory()); - - } - - @Override - public void tearDown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(URISupport.removeQuery(connector.getConnectUri()) + "?useKeepAlive=false&wireFormat.maxInactivityDuration=2000"); - } - - @Override - public void testCreateDurableConsumerCloseThenReconnect() throws Exception { - reconnectInExceptionListener = true; - makeConsumer(); - connection.setExceptionListener(this); - ((ActiveMQConnection) connection).addTransportListener(this); - assertTrue("inactive connection timedout", gotException.await(30, TimeUnit.SECONDS)); - assertNotNull("Got expected exception on close reconnect overlap: " + reconnectException, reconnectException); - } - - public void testCreateDurableConsumerSlowCloseThenReconnectTransportListener() throws Exception { - reconnectInTransportListener = true; - makeConsumer(); - connection.setExceptionListener(this); - ((ActiveMQConnection) connection).addTransportListener(this); - assertTrue("inactive connection timedout", gotException.await(30, TimeUnit.SECONDS)); - assertNull("No exception: " + reconnectException, reconnectException); - } - - @Override - public void onException(JMSException exception) { - LOG.info("Exception listener exception:" + exception); - if (reconnectInExceptionListener) { - try { - makeConsumer(); - } catch (Exception e) { - reconnectException = e; - } - - gotException.countDown(); - } - } - - @Override - public void onCommand(Object command) { - } - - @Override - public void onException(IOException error) { - LOG.info("Transport listener exception:" + error); - if (reconnectInTransportListener) { - try { - TimeUnit.MILLISECONDS.sleep(500); - makeConsumer(); - } catch (Exception e) { - reconnectException = e; - } - - gotException.countDown(); - } - } - - @Override - public void transportInterupted() { - } - - @Override - public void transportResumed() { - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableConsumerCloseAndReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableConsumerCloseAndReconnectTest.java deleted file mode 100644 index 11fc1b5f48..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableConsumerCloseAndReconnectTest.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.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.jms.Topic; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.test.TestSupport; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class DurableConsumerCloseAndReconnectTest extends TestSupport { - - protected static final long RECEIVE_TIMEOUT = 5000L; - private static final Logger LOG = LoggerFactory.getLogger(DurableConsumerCloseAndReconnectTest.class); - - BrokerService brokerService; - - protected Connection connection; - private Session session; - private MessageConsumer consumer; - private MessageProducer producer; - private Destination destination; - private int messageCount; - - private String vmConnectorURI; - - @Override - protected void setUp() throws Exception { - createBroker(); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - stopBroker(); - super.tearDown(); - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(vmConnectorURI); - } - - protected void createBroker() throws Exception { - brokerService = new BrokerService(); - brokerService.setUseJmx(false); - brokerService.setPersistent(false); - KahaDBPersistenceAdapter store = new KahaDBPersistenceAdapter(); - brokerService.setPersistenceAdapter(store); - brokerService.start(); - brokerService.waitUntilStarted(); - vmConnectorURI = brokerService.getVmConnectorURI().toString(); - } - - protected void stopBroker() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - } - - public void testDurableSubscriberReconnectMultipleTimes() throws Exception { - Connection dummyConnection = createConnection(); - dummyConnection.start(); - - makeConsumer(Session.AUTO_ACKNOWLEDGE); - closeConsumer(); - - publish(30); - - int counter = 1; - for (int i = 0; i < 15; i++) { - makeConsumer(Session.AUTO_ACKNOWLEDGE); - Message message = consumer.receive(RECEIVE_TIMEOUT); - assertTrue("Should have received a message!", message != null); - LOG.info("Received message " + counter++); - message = consumer.receive(RECEIVE_TIMEOUT); - assertTrue("Should have received a message!", message != null); - LOG.info("Received message " + counter++); - closeConsumer(); - } - - dummyConnection.close(); - } - - public void testCreateDurableConsumerCloseThenReconnect() throws Exception { - // force the server to stay up across both connection tests - Connection dummyConnection = createConnection(); - dummyConnection.start(); - - consumeMessagesDeliveredWhileConsumerClosed(); - - dummyConnection.close(); - - // now lets try again without one connection open - consumeMessagesDeliveredWhileConsumerClosed(); - } - - protected void consumeMessagesDeliveredWhileConsumerClosed() throws Exception { - // default to client ack for consumer - makeConsumer(); - closeConsumer(); - - publish(1); - - // wait a few moments for the close to really occur - Thread.sleep(1000); - - makeConsumer(); - - Message message = consumer.receive(RECEIVE_TIMEOUT); - assertTrue("Should have received a message!", message != null); - - closeConsumer(); - - LOG.info("Now lets create the consumer again and because we didn't ack, we should get it again"); - makeConsumer(); - - message = consumer.receive(RECEIVE_TIMEOUT); - assertTrue("Should have received a message!", message != null); - message.acknowledge(); - - closeConsumer(); - - LOG.info("Now lets create the consumer again and because we did ack, we should not get it again"); - makeConsumer(); - - message = consumer.receive(2000); - assertTrue("Should have no more messages left!", message == null); - - closeConsumer(); - - LOG.info("Lets publish one more message now"); - publish(1); - - makeConsumer(); - message = consumer.receive(RECEIVE_TIMEOUT); - assertTrue("Should have received a message!", message != null); - message.acknowledge(); - - closeConsumer(); - } - - protected void publish(int numMessages) throws Exception { - connection = createConnection(); - connection.start(); - - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - destination = createDestination(); - - producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - for (int i = 0; i < numMessages; i++) { - TextMessage msg = session.createTextMessage("This is a test: " + messageCount++); - producer.send(msg); - } - - producer.close(); - producer = null; - closeSession(); - } - - protected Destination createDestination() throws JMSException { - if (isTopic()) { - return session.createTopic(getSubject()); - } else { - return session.createQueue(getSubject()); - } - } - - protected boolean isTopic() { - return true; - } - - protected void closeConsumer() throws JMSException { - LOG.info("Closing the consumer"); - consumer.close(); - consumer = null; - closeSession(); - } - - protected void closeSession() throws JMSException { - session.close(); - session = null; - connection.close(); - connection = null; - } - - protected void makeConsumer() throws Exception { - makeConsumer(Session.CLIENT_ACKNOWLEDGE); - } - - protected void makeConsumer(int ackMode) throws Exception { - String durableName = getName(); - String clientID = getSubject(); - LOG.info("Creating a durable subscriber for clientID: " + clientID + " and durable name: " + durableName); - createSession(clientID, ackMode); - consumer = createConsumer(durableName); - } - - private MessageConsumer createConsumer(String durableName) throws JMSException { - if (destination instanceof Topic) { - return session.createDurableSubscriber((Topic) destination, durableName); - } else { - return session.createConsumer(destination); - } - } - - protected void createSession(String clientID, int ackMode) throws Exception { - connection = createConnection(); - connection.setClientID(clientID); - connection.start(); - - session = connection.createSession(false, ackMode); - destination = createDestination(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubDelayedUnsubscribeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubDelayedUnsubscribeTest.java deleted file mode 100644 index 42625ff337..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubDelayedUnsubscribeTest.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 ONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.management.ObjectName; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Vector; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.util.Wait; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -/* - * A cut down version of DurableSubProcessWithRestartTest that focuses on kahaDB file retention - */ -public class DurableSubDelayedUnsubscribeTest { - - private static final Logger LOG = LoggerFactory.getLogger(DurableSubDelayedUnsubscribeTest.class); - - private static final long RUNTIME = 2 * 60 * 1000; - private static final int CARGO_SIZE = 400; // max - private static final int MAX_CLIENTS = 15; - private static boolean ALLOW_SUBSCRIPTION_ABANDONMENT = true; - private static final Vector exceptions = new Vector<>(); - - private BrokerService broker; - private ActiveMQTopic topic; - - private ClientManager clientManager; - private Server server; - private HouseKeeper houseKeeper; - - private final ReentrantReadWriteLock processLock = new ReentrantReadWriteLock(true); - - @Test - public void testProcess() throws Exception { - - server.start(); - clientManager.start(); - - houseKeeper.start(); - - // Sleep to - Thread.sleep(RUNTIME); - - // inform message producer to stop - server.stopped = true; - - // add one Subscriber to the topic that will not be unsubscribed. - // should not have any pending messages in the kahadb store - Client lastClient = new Client(32000, ClientType.A); - lastClient.process(1000); - - // stop client manager from creating any more clients - clientManager.stopped = true; - - final BrokerService brokerService = this.broker; - - // Wait for all client subscription to be unsubscribed or swept away. - // Ensure we sleep longer than the housekeeper's sweep delay otherwise we can - // miss the fact that all durables that were abandoned do finally get cleaned up. - - // Wait for all clients to stop - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return clientManager.getClientCount() == 0; - } - }, Client.lifetime + TimeUnit.SECONDS.toMillis(10)); - - assertTrue("should have only one inactiveSubscriber subscribed but was: " + brokerService.getAdminView().getInactiveDurableTopicSubscribers().length, Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - return brokerService.getAdminView().getInactiveDurableTopicSubscribers().length == 1; - } - }, houseKeeper.SWEEP_DELAY * 2)); - - assertTrue("should be no subscribers subscribed but was: " + brokerService.getAdminView().getDurableTopicSubscribers().length, Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - return brokerService.getAdminView().getDurableTopicSubscribers().length == 0; - } - }, TimeUnit.MINUTES.toMillis(3))); - - processLock.writeLock().lock(); - - // check outcome. - - ObjectName[] subscribers = broker.getAdminView().getDurableTopicSubscribers(); - ObjectName[] inactiveSubscribers = broker.getAdminView().getInactiveDurableTopicSubscribers(); - final KahaDBPersistenceAdapter persistenceAdapter = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - - printDebugClientInfo(subscribers, inactiveSubscribers, persistenceAdapter); - - assertEquals("should have only one inactiveSubscriber subscribed", 1, broker.getAdminView().getInactiveDurableTopicSubscribers().length); - assertEquals("should be no subscribers subscribed", 0, broker.getAdminView().getDurableTopicSubscribers().length); - - final KahaDBPersistenceAdapter pa = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - assertTrue("should be less than 3 journal file left but was: " + persistenceAdapter.getStore().getJournal().getFileMap().size(), Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - return pa.getStore().getJournal().getFileMap().size() <= 3; - } - }, TimeUnit.MINUTES.toMillis(3))); - - // Be good and cleanup our mess a bit. - this.houseKeeper.shutdown(); - - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - - LOG.info("DONE."); - } - - private void printDebugClientInfo(ObjectName[] subscribers, - ObjectName[] inactiveSubscribers, - final KahaDBPersistenceAdapter pa) throws IOException { - - LOG.info("====>>> START DEBUG Subscriber INFO"); - - LOG.info("Number of subscribers subscribed as seen through JMX is" + subscribers.length); - - for (int i = 0; i < subscribers.length; i++) { - LOG.info("subscribers subscribed as seen throngh JMX: " + subscribers[i]); - } - - LOG.info("Number of inactiveSubscribers subscribed as seen through JMX is" + inactiveSubscribers.length); - - for (int i = 0; i < inactiveSubscribers.length; i++) { - LOG.info("subscribers subscribed as seen throngh JMX: " + inactiveSubscribers[i]); - } - - LOG.info("ClientManager.clients size is" + clientManager.clients.size()); - - for (int i = 0; i < clientManager.clients.size(); i++) { - LOG.info("clients is: " + clientManager.clients.get(i)); - } - - LOG.info("housekeep.subscriptions size is " + houseKeeper.abandonedSubscriptions.size()); - - for (int i = 0; i < houseKeeper.abandonedSubscriptions.size(); i++) { - LOG.info("housekeep is: " + houseKeeper.abandonedSubscriptions.get(i)); - } - - LOG.info("number of journal files left" + pa.getStore().getJournal().getFileMap().size()); - - LOG.info("====>>> END DEBUG Subscriber INFO"); - } - - /** - * Creates batch of messages in a transaction periodically. The last message - * in the transaction is always a special message what contains info about - * the whole transaction. - *

- * Notifies the clients about the created messages also. - */ - final class Server extends Thread { - - public boolean stopped; - final String url = "vm://" + DurableSubDelayedUnsubscribeTest.getName() + "?" + "jms.redeliveryPolicy.maximumRedeliveries=2&jms.redeliveryPolicy.initialRedeliveryDelay=500&" + "jms.producerWindowSize=20971520&jms.prefetchPolicy.all=100&" + "jms.copyMessageOnSend=false&jms.disableTimeStampsByDefault=false&" + "jms.alwaysSyncSend=true&jms.dispatchAsync=false&" + "jms.watchTopicAdvisories=false&" + "waitForStart=200&create=false"; - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - - final Object sendMutex = new Object(); - final String[] cargos = new String[500]; - - int transRover = 0; - int messageRover = 0; - - public Server() { - super("Server"); - setDaemon(true); - } - - @Override - public void run() { - try { - while (true) { - - if (stopped) { - // server should stop producing - break; - } - - Thread.sleep(500); - processLock.readLock().lock(); - try { - send(); - } finally { - processLock.readLock().unlock(); - } - } - } catch (Throwable e) { - exit("Server.run failed", e); - } - } - - public void send() throws JMSException { - // do not create new clients now - // ToDo: Test this case later. - synchronized (sendMutex) { - int trans = ++transRover; - boolean relevantTrans = random(2) > 1; - ClientType clientType = relevantTrans ? ClientType.randomClientType() : null; // sends - // this - // types - int count = random(200); - - LOG.info("Sending Trans[id=" + trans + ", count=" + count + ", clientType=" + clientType + "]"); - - Connection con = cf.createConnection(); - Session sess = con.createSession(true, Session.SESSION_TRANSACTED); - MessageProducer prod = sess.createProducer(null); - - for (int i = 0; i < count; i++) { - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setIntProperty("TRANS", trans); - String type = clientType != null ? clientType.randomMessageType() : ClientType.randomNonRelevantMessageType(); - message.setStringProperty("TYPE", type); - - if (CARGO_SIZE > 0) - message.setStringProperty("CARGO", getCargo(random(CARGO_SIZE))); - - prod.send(topic, message); - - } - - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setIntProperty("TRANS", trans); - message.setBooleanProperty("COMMIT", true); - message.setBooleanProperty("RELEVANT", relevantTrans); - prod.send(topic, message); - - sess.commit(); - LOG.info("Committed Trans[id=" + trans + ", count=" + count + ", clientType=" + clientType + "], ID=" + messageRover); - - sess.close(); - con.close(); - } - } - - private String getCargo(int length) { - if (length == 0) - return null; - - if (length < cargos.length) { - String result = cargos[length]; - if (result == null) { - result = getCargoImpl(length); - cargos[length] = result; - } - return result; - } - return getCargoImpl(length); - } - - private String getCargoImpl(int length) { - StringBuilder sb = new StringBuilder(length); - for (int i = length; --i >= 0; ) { - sb.append('a'); - } - return sb.toString(); - } - } - - /** - * Clients listen on different messages in the topic. The 'TYPE' property - * helps the client to select the proper messages. - */ - private enum ClientType { - A("a", "b", "c"), B("c", "d", "e"), C("d", "e", "f"), D("g", "h"); - - public final String[] messageTypes; - - public final String selector; - - ClientType(String... messageTypes) { - this.messageTypes = messageTypes; - - StringBuilder sb = new StringBuilder("TYPE in ("); - for (int i = 0; i < messageTypes.length; i++) { - if (i > 0) - sb.append(", "); - sb.append('\'').append(messageTypes[i]).append('\''); - } - sb.append(')'); - selector = sb.toString(); - } - - public static ClientType randomClientType() { - return values()[DurableSubDelayedUnsubscribeTest.random(values().length - 1)]; - } - - public final String randomMessageType() { - return messageTypes[DurableSubDelayedUnsubscribeTest.random(messageTypes.length - 1)]; - } - - public static String randomNonRelevantMessageType() { - return Integer.toString(DurableSubDelayedUnsubscribeTest.random(20)); - } - - @Override - public final String toString() { - return this.name() /* + '[' + selector + ']' */; - } - } - - /** - * Creates new cliens. - */ - private final class ClientManager extends Thread { - - private int clientRover = 0; - - private final CopyOnWriteArrayList clients = new CopyOnWriteArrayList<>(); - - private boolean stopped; - - public ClientManager() { - super("ClientManager"); - setDaemon(true); - } - - public int getClientCount() { - return clients.size(); - } - - @Override - public void run() { - try { - while (true) { - if (clients.size() < MAX_CLIENTS) { - - if (stopped) { - // get out, don't start any more threads - break; - } - processLock.readLock().lock(); - try { - createNewClient(); - } finally { - processLock.readLock().unlock(); - } - } - - int size = clients.size(); - sleepRandom(size * 3 * 1000, size * 6 * 1000); - } - } catch (Throwable e) { - exit("ClientManager.run failed.", e); - } - } - - private void createNewClient() throws JMSException { - ClientType type = ClientType.randomClientType(); - - Client client; - synchronized (server.sendMutex) { - client = new Client(++clientRover, type); - clients.add(client); - } - client.start(); - - LOG.info(client.toString() + " created. " + this); - } - - public void removeClient(Client client) { - clients.remove(client); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("ClientManager[count="); - sb.append(clients.size()); - sb.append(", clients="); - boolean sep = false; - for (Client client : clients) { - if (sep) - sb.append(", "); - else - sep = true; - sb.append(client.toString()); - } - sb.append(']'); - return sb.toString(); - } - } - - /** - * Consumes massages from a durable subscription. Goes online/offline - * periodically. Checks the incoming messages against the sent messages of - * the server. - */ - private final class Client extends Thread { - - String url = "failover:(tcp://localhost:61656?wireFormat.maxInactivityDuration=0)?" + "jms.watchTopicAdvisories=false&" + "jms.alwaysSyncSend=true&jms.dispatchAsync=true&" + "jms.producerWindowSize=20971520&" + "jms.copyMessageOnSend=false&" + "initialReconnectDelay=100&maxReconnectDelay=30000&" + "useExponentialBackOff=true"; - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - - public static final String SUBSCRIPTION_NAME = "subscription"; - - private final int id; - private final String conClientId; - - public static final int lifetime = 60 * 1000; - private final int online = 1 * 1000; - private final int offline = 59 * 1000; - - private final ClientType clientType; - private final String selector; - - public Client(int id, ClientType clientType) throws JMSException { - super("Client" + id); - setDaemon(true); - - this.id = id; - conClientId = "cli" + id; - this.clientType = clientType; - selector = "(COMMIT = true and RELEVANT = true) or " + clientType.selector; - - subscribe(); - } - - @Override - public void run() { - // long end = System.currentTimeMillis() + lifetime.next(); - long end = System.currentTimeMillis() + lifetime; - try { - boolean sleep = false; - while (true) { - long max = end - System.currentTimeMillis(); - if (max <= 0) - break; - - if (sleep) - Thread.sleep(offline); - // offline.sleepRandom(); - else - sleep = true; - - processLock.readLock().lock(); - try { - process(online); - } finally { - processLock.readLock().unlock(); - } - } - - // 50% unsubscribe, 50% abandon subscription - if (!ALLOW_SUBSCRIPTION_ABANDONMENT) { - unsubscribe(); - ALLOW_SUBSCRIPTION_ABANDONMENT = true; - } else { - - LOG.info("Client abandon the subscription. " + this); - - // housekeeper should sweep these abandoned subscriptions - houseKeeper.abandonedSubscriptions.add(conClientId); - ALLOW_SUBSCRIPTION_ABANDONMENT = false; - } - } catch (Throwable e) { - exit(toString() + " failed.", e); - } - - clientManager.removeClient(this); - LOG.info(toString() + " DONE."); - } - - private void process(long processingTime) throws JMSException { - long end = System.currentTimeMillis() + processingTime; - long hardEnd = end + 20000; // wait to finish the transaction. - boolean inTransaction = false; - int transCount = 0; - - LOG.info(toString() + " ONLINE."); - Connection con = openConnection(); - Session sess = con.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = sess.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, false); - try { - do { - long max = end - System.currentTimeMillis(); - if (max <= 0) { - if (!inTransaction) - break; - - max = hardEnd - System.currentTimeMillis(); - if (max <= 0) - exit("" + this + " failed: Transaction is not finished."); - } - - Message message = consumer.receive(max); - if (message == null) - continue; - - if (message.propertyExists("COMMIT")) { - message.acknowledge(); // CLIENT_ACKNOWLEDGE - - LOG.info("Received Trans[id=" + message.getIntProperty("TRANS") + ", count=" + transCount + "] in " + this + "."); - - inTransaction = false; - transCount = 0; - } else { - inTransaction = true; - transCount++; - } - } while (true); - } finally { - sess.close(); - con.close(); - LOG.info(toString() + " OFFLINE."); - } - } - - private Connection openConnection() throws JMSException { - Connection con = cf.createConnection(); - con.setClientID(conClientId); - con.start(); - return con; - } - - private void subscribe() throws JMSException { - Connection con = openConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, true); - session.close(); - con.close(); - } - - private void unsubscribe() throws JMSException { - Connection con = openConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.unsubscribe(SUBSCRIPTION_NAME); - session.close(); - con.close(); - } - - @Override - public String toString() { - return "Client[id=" + id + ", type=" + clientType + "]"; - } - } - - /** - * Sweeps out not-used durable subscriptions. - */ - private final class HouseKeeper extends Thread { - - private final AtomicBoolean done = new AtomicBoolean(); - - public final long SWEEP_DELAY = TimeUnit.MINUTES.toMillis(3); - - private HouseKeeper() { - super("HouseKeeper"); - setDaemon(true); - } - - public final CopyOnWriteArrayList abandonedSubscriptions = new CopyOnWriteArrayList<>(); - - public void shutdown() throws Exception { - done.set(true); - - // In case we are sleeping, abort the sleep. - this.interrupt(); - - // Wait for run to complete. - this.join(TimeUnit.MINUTES.toMillis(SWEEP_DELAY)); - - // Ensure all abandoned subscriptions get wiped. - if (!abandonedSubscriptions.isEmpty()) { - this.sweep(); - } - } - - @Override - public void run() { - while (!done.get()) { - try { - Thread.sleep(SWEEP_DELAY); - - processLock.readLock().lock(); - try { - sweep(); - } finally { - processLock.readLock().unlock(); - } - } catch (InterruptedException ex) { - break; - } catch (Throwable e) { - Exception log = new Exception("HouseKeeper failed.", e); - log.printStackTrace(); - } - } - } - - private void sweep() throws Exception { - LOG.info("Housekeeper sweeping."); - - int closed = 0; - ArrayList sweeped = new ArrayList<>(); - try { - for (String clientId : abandonedSubscriptions) { - LOG.info("Sweeping out subscription of " + clientId + "."); - broker.getAdminView().destroyDurableSubscriber(clientId, Client.SUBSCRIPTION_NAME); - sweeped.add(clientId); - closed++; - } - } catch (Exception ignored) { - LOG.info("Ex on destroy sub " + ignored); - } finally { - abandonedSubscriptions.removeAll(sweeped); - } - - LOG.info("Housekeeper sweeped out " + closed + " subscriptions."); - } - } - - public static int random(int max) { - return (int) (Math.random() * (max + 1)); - } - - public static int random(int min, int max) { - return random(max - min) + min; - } - - public static void sleepRandom(int maxMillis) throws InterruptedException { - Thread.sleep(random(maxMillis)); - } - - public static void sleepRandom(int minMillis, int maxMillis) throws InterruptedException { - Thread.sleep(random(minMillis, maxMillis)); - } - - public static final class Random { - - final int min; - final int max; - - Random(int min, int max) { - this.min = min; - this.max = max; - } - - public int next() { - return random(min, max); - } - - public void sleepRandom() throws InterruptedException { - DurableSubDelayedUnsubscribeTest.sleepRandom(min, max); - } - } - - public static void exit(String message) { - exit(message, null); - } - - public static void exit(String message, Throwable e) { - Throwable cause = new RuntimeException(message, e); - LOG.error(message, cause); - exceptions.add(cause); - fail(cause.toString()); - } - - @Before - public void setUp() throws Exception { - topic = new ActiveMQTopic("TopicT"); - startBroker(); - - clientManager = new ClientManager(); - server = new Server(); - houseKeeper = new HouseKeeper(); - } - - @After - public void tearDown() throws Exception { - destroyBroker(); - } - - private void startBroker() throws Exception { - startBroker(true); - } - - private void startBroker(boolean deleteAllMessages) throws Exception { - if (broker != null) - return; - - broker = BrokerFactory.createBroker("broker:(vm://" + getName() + ")"); - broker.setBrokerName(getName()); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - - File kahadbData = new File("activemq-data/" + getName() + "-kahadb"); - if (deleteAllMessages) - delete(kahadbData); - - broker.setPersistent(true); - KahaDBPersistenceAdapter kahadb = new KahaDBPersistenceAdapter(); - kahadb.setDirectory(kahadbData); - kahadb.setJournalMaxFileLength(512 * 1024); - broker.setPersistenceAdapter(kahadb); - - broker.addConnector("tcp://localhost:61656"); - - broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getTempUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getStoreUsage().setLimit(256 * 1024 * 1024); - - broker.start(); - } - - protected static String getName() { - return "DurableSubProcessWithRestartTest"; - } - - private static boolean delete(File path) { - if (path == null) - return true; - - if (path.isDirectory()) { - for (File file : path.listFiles()) { - delete(file); - } - } - return path.delete(); - } - - private void destroyBroker() throws Exception { - if (broker == null) - return; - - broker.stop(); - broker = null; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubInBrokerNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubInBrokerNetworkTest.java deleted file mode 100644 index e8ba0ecf91..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubInBrokerNetworkTest.java +++ /dev/null @@ -1,179 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.Session; -import javax.jms.Topic; -import javax.jms.TopicSubscriber; -import javax.management.ObjectName; -import java.net.URI; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.network.DiscoveryNetworkConnector; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.network.NetworkTestSupport; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Tests durable topic subscriptions inside a network of brokers. - * - * @author tmielke - */ -public class DurableSubInBrokerNetworkTest extends NetworkTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(DurableSubInBrokerNetworkTest.class); - // protected BrokerService localBroker; - private final String subName = "Subscriber1"; - private final String subName2 = "Subscriber2"; - private final String topicName = "TEST.FOO"; - - @Override - protected void setUp() throws Exception { - useJmx = true; - super.setUp(); - - URI ncUri = new URI("static:(" + connector.getConnectUri().toString() + ")"); - NetworkConnector nc = new DiscoveryNetworkConnector(ncUri); - nc.setDuplex(true); - remoteBroker.addNetworkConnector(nc); - nc.start(); - } - - @Override - protected void tearDown() throws Exception { - if (remoteBroker.isStarted()) { - remoteBroker.stop(); - remoteBroker.waitUntilStopped(); - } - if (broker.isStarted()) { - broker.stop(); - broker.waitUntilStopped(); - } - super.tearDown(); - } - - /** - * Creates a durable topic subscription, checks that it is propagated - * in the broker network, removes the subscription and checks that - * the subscription is removed from remote broker as well. - * - * @throws Exception - */ - public void testDurableSubNetwork() throws Exception { - LOG.info("testDurableSubNetwork started."); - - // create durable sub - ActiveMQConnectionFactory fact = new ActiveMQConnectionFactory(connector.getConnectUri().toString()); - Connection conn = fact.createConnection(); - conn.setClientID("clientID1"); - Session session = conn.createSession(false, 1); - Destination dest = session.createTopic(topicName); - TopicSubscriber sub = session.createDurableSubscriber((Topic) dest, subName); - LOG.info("Durable subscription of name " + subName + "created."); - Thread.sleep(100); - - // query durable sub on local and remote broker - // raise an error if not found - - assertTrue(foundSubInLocalBroker(subName)); - - assertTrue(foundSubInRemoteBrokerByTopicName(topicName)); - - // unsubscribe from durable sub - sub.close(); - session.unsubscribe(subName); - LOG.info("Unsubscribed from durable subscription."); - Thread.sleep(100); - - // query durable sub on local and remote broker - // raise an error if its not removed from both brokers - assertFalse(foundSubInLocalBroker(subName)); - - assertFalse("Durable subscription not unregistered on remote broker", foundSubInRemoteBrokerByTopicName(topicName)); - - } - - public void testTwoDurableSubsInNetworkWithUnsubscribe() throws Exception { - - // create 1st durable sub to topic TEST.FOO - ActiveMQConnectionFactory fact = new ActiveMQConnectionFactory(connector.getConnectUri().toString()); - Connection conn = fact.createConnection(); - conn.setClientID("clientID1"); - Session session = conn.createSession(false, 1); - Destination dest = session.createTopic(topicName); - TopicSubscriber sub = session.createDurableSubscriber((Topic) dest, subName); - LOG.info("Durable subscription of name " + subName + "created."); - TopicSubscriber sub2 = session.createDurableSubscriber((Topic) dest, subName2); - LOG.info("Durable subscription of name " + subName2 + "created."); - - Thread.sleep(100); - - // query durable sub on local and remote broker - // raise an error if not found - - assertTrue(foundSubInLocalBroker(subName)); - assertTrue(foundSubInLocalBroker(subName2)); - - assertTrue(foundSubInRemoteBrokerByTopicName(topicName)); - - // unsubscribe from durable sub - sub.close(); - session.unsubscribe(subName); - LOG.info("Unsubscribed from durable subscription."); - Thread.sleep(100); - - // query durable sub on local and remote broker - assertFalse(foundSubInLocalBroker(subName)); - assertTrue(foundSubInLocalBroker(subName2)); - - assertTrue("Durable subscription should still be on remote broker", foundSubInRemoteBrokerByTopicName(topicName)); - - sub2.close(); - session.unsubscribe(subName2); - - Thread.sleep(100); - - assertFalse(foundSubInLocalBroker(subName2)); - - assertFalse("Durable subscription not unregistered on remote broker", foundSubInRemoteBrokerByTopicName(topicName)); - - } - - private boolean foundSubInRemoteBrokerByTopicName(String topicName) throws Exception { - boolean foundSub = false; - ObjectName[] subs = remoteBroker.getAdminView().getDurableTopicSubscribers(); - for (int i = 0; i < subs.length; i++) { - if (subs[i].toString().contains("destinationName=" + topicName)) - foundSub = true; - } - return foundSub; - } - - private boolean foundSubInLocalBroker(String subName) throws Exception { - boolean foundSub = false; - ObjectName[] subs = broker.getAdminView().getDurableTopicSubscribers(); - - for (int i = 0; i < subs.length; i++) { - if (subs[i].toString().contains(subName)) - foundSub = true; - } - return foundSub; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessConcurrentCommitActivateNoDuplicateTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessConcurrentCommitActivateNoDuplicateTest.java deleted file mode 100644 index cd509a67c7..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessConcurrentCommitActivateNoDuplicateTest.java +++ /dev/null @@ -1,879 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR ONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.io.File; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashSet; -import java.util.Vector; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ActiveMQMessageConsumer; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.leveldb.LevelDBStore; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.util.ThreadTracker; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertTrue; - -public class DurableSubProcessConcurrentCommitActivateNoDuplicateTest { - - private static final Logger LOG = LoggerFactory.getLogger(DurableSubProcessConcurrentCommitActivateNoDuplicateTest.class); - public static final long RUNTIME = 5 * 60 * 1000; - - public static final int SERVER_SLEEP = 500; // max - public static final int CARGO_SIZE = 600; // max - - public static final int MAX_CLIENTS = 2; - public static final Random CLIENT_LIFETIME = new Random(30 * 1000, 2 * 60 * 1000); - public static final Random CLIENT_ONLINE = new Random(30 * 1000, 40 * 1000); - public static final Random CLIENT_OFFLINE = new Random(1 * 1000, 10 * 1000); - - public static final int CLIENT_OFFLINE_DURING_COMMIT = 2; // random(x) == x - - public static final Persistence PERSISTENT_ADAPTER = Persistence.KAHADB; - - public static final long BROKER_RESTART = -2 * 60 * 1000; - - public static final boolean ALLOW_SUBSCRIPTION_ABANDONMENT = true; - public static final boolean CHECK_REDELIVERY = true; - - private BrokerService broker; - private ActiveMQTopic topic; - - private ClientManager clientManager; - private Server server; - private HouseKeeper houseKeeper; - - private final ReentrantReadWriteLock processLock = new ReentrantReadWriteLock(true); - private int restartCount = 0; - private final AtomicInteger onlineCount = new AtomicInteger(0); - static final Vector exceptions = new Vector<>(); - - // long form of test that found https://issues.apache.org/jira/browse/AMQ-3805 - @Ignore("short version in org.apache.activemq.usecases.DurableSubscriptionOfflineTest.testNoDuplicateOnConcurrentSendTranCommitAndActivate" + " and org.apache.activemq.usecases.DurableSubscriptionOfflineTest.testOrderOnActivateDeactivate") - @Test - public void testProcess() { - try { - server.start(); - clientManager.start(); - - if (ALLOW_SUBSCRIPTION_ABANDONMENT) - houseKeeper.start(); - - if (BROKER_RESTART <= 0) - Thread.sleep(RUNTIME); - else { - long end = System.currentTimeMillis() + RUNTIME; - - while (true) { - long now = System.currentTimeMillis(); - if (now > end) - break; - - now = end - now; - now = now < BROKER_RESTART ? now : BROKER_RESTART; - Thread.sleep(now); - - restartBroker(); - } - } - } catch (Throwable e) { - exit("ProcessTest.testProcess failed.", e); - } - - //allow the clients to unsubscribe before finishing - clientManager.setEnd(true); - try { - Thread.sleep(60 * 1000); - } catch (InterruptedException e) { - exit("ProcessTest.testProcess failed.", e); - } - - server.done = true; - - try { - server.join(60 * 1000); - } catch (Exception ignored) { - } - processLock.writeLock().lock(); - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - LOG.info("DONE."); - } - - private void restartBroker() throws Exception { - LOG.info("Broker restart: waiting for components."); - - processLock.writeLock().lock(); - try { - destroyBroker(); - startBroker(false); - - restartCount++; - LOG.info("Broker restarted. count: " + restartCount); - } finally { - processLock.writeLock().unlock(); - } - } - - /** - * Creates batch of messages in a transaction periodically. The last message - * in the transaction is always a special message what contains info about - * the whole transaction. - *

- * Notifies the clients about the created messages also. - */ - final class Server extends Thread { - - final String url = "vm://" + DurableSubProcessConcurrentCommitActivateNoDuplicateTest.getName() + "?" + "jms.redeliveryPolicy.maximumRedeliveries=2&jms.redeliveryPolicy.initialRedeliveryDelay=500&" + "jms.producerWindowSize=20971520&jms.prefetchPolicy.all=100&" + "jms.copyMessageOnSend=false&jms.disableTimeStampsByDefault=false&" + "jms.alwaysSyncSend=true&jms.dispatchAsync=false&" + "jms.watchTopicAdvisories=false&" + "waitForStart=200&create=false"; - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - - final Object sendMutex = new Object(); - final String[] cargos = new String[500]; - - int transRover = 0; - int messageRover = 0; - public volatile int committingTransaction = -1; - public boolean done = false; - - public Server() { - super("Server"); - setPriority(Thread.MIN_PRIORITY); - setDaemon(true); - } - - @Override - public void run() { - try { - while (!done) { - - Thread.sleep(1000); - - processLock.readLock().lock(); - try { - send(); - } finally { - processLock.readLock().unlock(); - } - } - } catch (Throwable e) { - exit("Server.run failed", e); - } - } - - public void send() throws JMSException { - // do not create new clients now - // ToDo: Test this case later. - synchronized (sendMutex) { - int trans = ++transRover; - boolean relevantTrans = true; //random(2) > 1; - ClientType clientType = relevantTrans ? ClientType.randomClientType() : null; // sends this types - //int count = random(500, 700); - int count = 1000; - - LOG.info("Sending Trans[id=" + trans + ", count=" + count + ", clientType=" + clientType + ", firstID=" + (messageRover + 1) + "]"); - - Connection con = cf.createConnection(); - Session sess = con.createSession(true, Session.SESSION_TRANSACTED); - MessageProducer prod = sess.createProducer(null); - - for (int i = 0; i < count; i++) { - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setIntProperty("TRANS", trans); - String type = clientType != null ? clientType.randomMessageType() : ClientType.randomNonRelevantMessageType(); - message.setStringProperty("TYPE", type); - - if (CARGO_SIZE > 0) - message.setStringProperty("CARGO", getCargo(random(CARGO_SIZE))); - - prod.send(topic, message); - clientManager.onServerMessage(message); - } - - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setIntProperty("TRANS", trans); - message.setBooleanProperty("COMMIT", true); - message.setBooleanProperty("RELEVANT", relevantTrans); - prod.send(topic, message); - clientManager.onServerMessage(message); - - committingTransaction = trans; - sess.commit(); - committingTransaction = -1; - - LOG.info("Committed Trans[id=" + trans + ", count=" + count + ", clientType=" + clientType + "], ID=" + messageRover); - - sess.close(); - con.close(); - } - } - - private String getCargo(int length) { - if (length == 0) - return null; - - if (length < cargos.length) { - String result = cargos[length]; - if (result == null) { - result = getCargoImpl(length); - cargos[length] = result; - } - return result; - } - return getCargoImpl(length); - } - - private String getCargoImpl(int length) { - StringBuilder sb = new StringBuilder(length); - for (int i = length; --i >= 0; ) { - sb.append('a'); - } - return sb.toString(); - } - } - - /** - * Clients listen on different messages in the topic. The 'TYPE' property - * helps the client to select the proper messages. - */ - private enum ClientType { - A("a", "b", "c"), B("c", "d", "e"), C("d", "e", "f"), D("g", "h"); - - public final String[] messageTypes; - public final HashSet messageTypeSet; - public final String selector; - - ClientType(String... messageTypes) { - this.messageTypes = messageTypes; - messageTypeSet = new HashSet<>(Arrays.asList(messageTypes)); - - StringBuilder sb = new StringBuilder("TYPE in ("); - for (int i = 0; i < messageTypes.length; i++) { - if (i > 0) - sb.append(", "); - sb.append('\'').append(messageTypes[i]).append('\''); - } - sb.append(')'); - selector = sb.toString(); - } - - public static ClientType randomClientType() { - return values()[DurableSubProcessConcurrentCommitActivateNoDuplicateTest.random(values().length - 1)]; - } - - public final String randomMessageType() { - return messageTypes[DurableSubProcessConcurrentCommitActivateNoDuplicateTest.random(messageTypes.length - 1)]; - } - - public static String randomNonRelevantMessageType() { - return Integer.toString(DurableSubProcessConcurrentCommitActivateNoDuplicateTest.random(20)); - } - - public final boolean isRelevant(String messageType) { - return messageTypeSet.contains(messageType); - } - - @Override - public final String toString() { - return this.name() /* + '[' + selector + ']' */; - } - } - - /** - * Creates new cliens. - */ - private final class ClientManager extends Thread { - - private int clientRover = 0; - - private final CopyOnWriteArrayList clients = new CopyOnWriteArrayList<>(); - - private boolean end; - - public ClientManager() { - super("ClientManager"); - setDaemon(true); - } - - public synchronized void setEnd(boolean end) { - this.end = end; - - } - - @Override - public void run() { - try { - while (true) { - if (clients.size() < MAX_CLIENTS && !end) { - processLock.readLock().lock(); - try { - createNewClient(); - } finally { - processLock.readLock().unlock(); - } - } - - int size = clients.size(); - //sleepRandom(1000, 4000); - Thread.sleep(100); - } - } catch (Throwable e) { - exit("ClientManager.run failed.", e); - } - } - - private void createNewClient() throws JMSException { - ClientType type = ClientType.randomClientType(); - - Client client; - synchronized (server.sendMutex) { - client = new Client(++clientRover, type, CLIENT_LIFETIME, CLIENT_ONLINE, CLIENT_OFFLINE); - clients.add(client); - } - client.start(); - - LOG.info(client.toString() + " created. " + this); - } - - public void removeClient(Client client) { - clients.remove(client); - } - - public void onServerMessage(Message message) throws JMSException { - for (Client client : clients) { - client.onServerMessage(message); - } - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("ClientManager[count="); - sb.append(clients.size()); - sb.append(", clients="); - boolean sep = false; - for (Client client : clients) { - if (sep) - sb.append(", "); - else - sep = true; - sb.append(client.toString()); - } - sb.append(']'); - return sb.toString(); - } - } - - /** - * Consumes massages from a durable subscription. Goes online/offline - * periodically. Checks the incoming messages against the sent messages of - * the server. - */ - private final class Client extends Thread { - - String url = "failover:(tcp://localhost:61656?wireFormat.maxInactivityDuration=0)?" + "jms.watchTopicAdvisories=false&" + "jms.alwaysSyncSend=true&jms.dispatchAsync=true&" + "jms.producerWindowSize=20971520&" + "jms.copyMessageOnSend=false&" + "jms.sendAcksAsync=false&" + "initialReconnectDelay=100&maxReconnectDelay=30000&" + "useExponentialBackOff=true"; - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - - public static final String SUBSCRIPTION_NAME = "subscription"; - - private final int id; - private final String conClientId; - - private final Random lifetime; - private final Random online; - private final Random offline; - - private final ClientType clientType; - private final String selector; - - private final ConcurrentLinkedQueue waitingList = new ConcurrentLinkedQueue<>(); - private final HashSet processed = CHECK_REDELIVERY ? new HashSet(10000) : null; - - private ActiveMQMessageConsumer consumer = null; - - public Client(int id, ClientType clientType, Random lifetime, Random online, Random offline) throws JMSException { - super("Client" + id); - setDaemon(true); - - this.id = id; - conClientId = "cli" + id; - this.clientType = clientType; - selector = "(COMMIT = true and RELEVANT = true) or " + clientType.selector; - - this.lifetime = lifetime; - this.online = online; - this.offline = offline; - - subscribe(); - } - - @Override - public void run() { - long end = System.currentTimeMillis() + 60000; - try { - boolean sleep = false; - while (true) { - long max = end - System.currentTimeMillis(); - if (max <= 0) - break; - - /* - if (sleep) - offline.sleepRandom(); - else - sleep = true; - */ - - Thread.sleep(100); - - processLock.readLock().lock(); - onlineCount.incrementAndGet(); - try { - process(online.next()); - } finally { - onlineCount.decrementAndGet(); - processLock.readLock().unlock(); - } - } - - if (!ALLOW_SUBSCRIPTION_ABANDONMENT || random(1) > 0) - unsubscribe(); - else { - LOG.info("Client abandon the subscription. " + this); - - // housekeeper should sweep these abandoned subscriptions - houseKeeper.abandonedSubscriptions.add(conClientId); - } - } catch (Throwable e) { - exit(toString() + " failed.", e); - } - - clientManager.removeClient(this); - LOG.info(toString() + " DONE."); - } - - private void process(long millis) throws JMSException { - //long end = System.currentTimeMillis() + millis; - long end = System.currentTimeMillis() + 200; - long hardEnd = end + 20000; // wait to finish the transaction. - boolean inTransaction = false; - int transCount = 0; - - Connection con = openConnection(); - Session sess = con.createSession(false, Session.CLIENT_ACKNOWLEDGE); - consumer = (ActiveMQMessageConsumer) sess.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, false); - LOG.info(toString() + " ONLINE."); - try { - do { - long max = end - System.currentTimeMillis(); - if (max <= 0) { - if (!inTransaction) { - LOG.info(toString() + " done after no work!"); - break; - } - - max = hardEnd - System.currentTimeMillis(); - if (max <= 0) - exit("" + this + " failed: Transaction is not finished."); - } - - Message message = consumer.receive(max); - if (message == null) - continue; - - onClientMessage(message); - - if (message.propertyExists("COMMIT")) { - message.acknowledge(); // CLIENT_ACKNOWLEDGE - - int trans = message.getIntProperty("TRANS"); - LOG.info("Received Trans[id=" + trans + ", count=" + transCount + "] in " + this + "."); - - inTransaction = false; - transCount = 0; - - int committing = server.committingTransaction; - if (committing == trans) { - LOG.info("Going offline during transaction commit. messageID=" + message.getIntProperty("ID")); - break; - } - } else { - inTransaction = true; - transCount++; - if (1 == transCount) { - LOG.info("In Trans[id=" + message.getIntProperty("TRANS") + "] first ID=" + message.getIntProperty("ID")); - } - } - } while (true); - } finally { - sess.close(); - con.close(); - - LOG.info(toString() + " OFFLINE."); - - // Check if the messages are in the waiting - // list for long time. - Message topMessage = waitingList.peek(); - if (topMessage != null) - checkDeliveryTime(topMessage); - } - } - - public void onServerMessage(Message message) throws JMSException { - if (Boolean.TRUE.equals(message.getObjectProperty("COMMIT"))) { - if (Boolean.TRUE.equals(message.getObjectProperty("RELEVANT"))) - waitingList.add(message); - } else { - String messageType = message.getStringProperty("TYPE"); - if (clientType.isRelevant(messageType)) - waitingList.add(message); - } - } - - public void onClientMessage(Message message) { - Message serverMessage = waitingList.poll(); - try { - Integer receivedId = (Integer) message.getObjectProperty("ID"); - if (processed != null && processed.contains(receivedId)) - LOG.info("! Message has been processed before. " + this + " redeliveredFlag=" + message.getJMSRedelivered() + ", message = " + message); - - if (serverMessage == null) - exit("" + this + " failed: There is no next server message, but received: " + message); - - Integer serverId = (Integer) serverMessage.getObjectProperty("ID"); - if (receivedId == null || serverId == null) - exit("" + this + " failed: message ID not found.\r\n" + " received: " + message + "\r\n" + " server: " + serverMessage); - - if (!serverId.equals(receivedId)) { - StringBuilder missingList = new StringBuilder(); - Object lastTrans = null; - int transCount = 0; - Message nextServerMessage = serverMessage; - do { - Integer nextServerId = (Integer) nextServerMessage.getObjectProperty("ID"); - if (nextServerId.equals(receivedId)) { - if (lastTrans != null) - missingList.append("Missing TRANS=").append(lastTrans).append(", size=").append(transCount).append("\r\n"); - break; - } - - Object trans = nextServerMessage.getObjectProperty("TRANS"); - if (!trans.equals(lastTrans)) { - if (lastTrans != null) - missingList.append("Missing TRANS=").append(lastTrans).append(", size=").append(transCount).append("\r\n"); - lastTrans = trans; - transCount = 1; - } else - transCount++; - } while ((nextServerMessage = waitingList.poll()) != null); - - exit("Missing messages!\r\n" + missingList + - "Received message: " + message + "\r\n" + - "Expected message: " + serverMessage); - } - - checkDeliveryTime(message); - - if (processed != null) - processed.add(receivedId); - } catch (Throwable e) { - exit("" + this + ".onClientMessage failed.\r\n" + " received: " + message + "\r\n" + " server: " + serverMessage, e); - } - } - - /** - * Checks if the message was not delivered fast enough. - */ - public void checkDeliveryTime(Message message) throws JMSException { - long creation = message.getJMSTimestamp(); - long min = System.currentTimeMillis() - (offline.max + online.min) * (BROKER_RESTART > 0 ? 4 : 1); - - if (false && min > creation) { - SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss.SSS"); - exit("" + this + ".checkDeliveryTime failed. Message time: " + df.format(new Date(creation)) + ", min: " + df.format(new Date(min)) + "\r\n" + message); - } - } - - private Connection openConnection() throws JMSException { - Connection con = cf.createConnection(); - con.setClientID(conClientId); - ((ActiveMQConnection) con).setCloseTimeout(60000); - con.start(); - return con; - } - - private void subscribe() throws JMSException { - processLock.readLock().lock(); - try { - Connection con = openConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, true); - session.close(); - con.close(); - } finally { - processLock.readLock().unlock(); - } - } - - private void unsubscribe() throws JMSException { - processLock.readLock().lock(); - LOG.info("Unsubscribe: " + this); - try { - Connection con = openConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.unsubscribe(SUBSCRIPTION_NAME); - session.close(); - con.close(); - } finally { - processLock.readLock().unlock(); - } - } - - @Override - public String toString() { - return "Client[id=" + id + ", type=" + clientType + "] consumerId=" + (consumer != null ? consumer.getConsumerId() : "null"); - } - } - - /** - * Sweeps out not-used durable subscriptions. - */ - private final class HouseKeeper extends Thread { - - private HouseKeeper() { - super("HouseKeeper"); - setDaemon(true); - } - - public final CopyOnWriteArrayList abandonedSubscriptions = new CopyOnWriteArrayList<>(); - - @Override - public void run() { - while (true) { - try { - Thread.sleep(3 * 60 * 1000); - - processLock.readLock().lock(); - try { - sweep(); - } finally { - processLock.readLock().unlock(); - } - } catch (InterruptedException ex) { - break; - } catch (Throwable e) { - Exception log = new Exception("HouseKeeper failed.", e); - log.printStackTrace(); - } - } - } - - private void sweep() throws Exception { - LOG.info("Housekeeper sweeping."); - - int closed = 0; - ArrayList sweeped = new ArrayList<>(); - try { - for (String clientId : abandonedSubscriptions) { - LOG.info("Sweeping out subscription of " + clientId + "."); - broker.getAdminView().destroyDurableSubscriber(clientId, Client.SUBSCRIPTION_NAME); - sweeped.add(clientId); - closed++; - } - } catch (Exception ignored) { - LOG.info("Ex on destroy sub " + ignored); - } finally { - abandonedSubscriptions.removeAll(sweeped); - } - - LOG.info("Housekeeper sweeped out " + closed + " subscriptions."); - } - } - - public static int random(int max) { - return (int) (Math.random() * (max + 1)); - } - - public static int random(int min, int max) { - return random(max - min) + min; - } - - public static void sleepRandom(int maxMillis) throws InterruptedException { - Thread.sleep(random(maxMillis)); - } - - public static void sleepRandom(int minMillis, int maxMillis) throws InterruptedException { - Thread.sleep(random(minMillis, maxMillis)); - } - - public static final class Random { - - final int min; - final int max; - - Random(int min, int max) { - this.min = min; - this.max = max; - } - - public int next() { - return random(min, max); - } - - public void sleepRandom() throws InterruptedException { - DurableSubProcessConcurrentCommitActivateNoDuplicateTest.sleepRandom(min, max); - } - } - - public static void exit(String message) { - exit(message, null); - } - - public static void exit(String message, Throwable e) { - Throwable cause = new RuntimeException(message, e); - LOG.error(message, cause); - exceptions.add(cause); - ThreadTracker.result(); - //fail(cause.toString()); - System.exit(-9); - } - - @Before - public void setUp() throws Exception { - topic = new ActiveMQTopic("TopicT"); - startBroker(); - - clientManager = new ClientManager(); - server = new Server(); - houseKeeper = new HouseKeeper(); - - } - - @After - public void tearDown() throws Exception { - destroyBroker(); - } - - private enum Persistence { - MEMORY, LEVELDB, KAHADB - } - - private void startBroker() throws Exception { - startBroker(true); - } - - private void startBroker(boolean deleteAllMessages) throws Exception { - if (broker != null) - return; - - broker = BrokerFactory.createBroker("broker:(vm://" + getName() + ")"); - broker.setBrokerName(getName()); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - - switch (PERSISTENT_ADAPTER) { - case MEMORY: - broker.setPersistent(false); - break; - - case LEVELDB: - File amqData = new File("activemq-data/" + getName() + "-leveldb"); - if (deleteAllMessages) - delete(amqData); - - broker.setPersistent(true); - LevelDBStore amq = new LevelDBStore(); - amq.setDirectory(amqData); - broker.setPersistenceAdapter(amq); - break; - - case KAHADB: - File kahadbData = new File("activemq-data/" + getName() + "-kahadb"); - if (deleteAllMessages) - delete(kahadbData); - - broker.setPersistent(true); - KahaDBPersistenceAdapter kahadb = new KahaDBPersistenceAdapter(); - kahadb.setDirectory(kahadbData); - kahadb.setJournalMaxFileLength(5 * 1024 * 1024); - broker.setPersistenceAdapter(kahadb); - break; - } - - broker.addConnector("tcp://localhost:61656"); - - broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getTempUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getStoreUsage().setLimit(1024 * 1024 * 1024); - - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setMaxAuditDepth(20000); - policyMap.setDefaultEntry(defaultEntry); - broker.setDestinationPolicy(policyMap); - broker.start(); - } - - protected static String getName() { - return "DurableSubProcessWithRestartTest"; - } - - private static boolean delete(File path) { - if (path == null) - return true; - - if (path.isDirectory()) { - for (File file : path.listFiles()) { - delete(file); - } - } - return path.delete(); - } - - private void destroyBroker() throws Exception { - if (broker == null) - return; - - broker.stop(); - broker = null; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessMultiRestartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessMultiRestartTest.java deleted file mode 100644 index d4c3a07fe8..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessMultiRestartTest.java +++ /dev/null @@ -1,405 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR ONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.io.File; -import java.io.IOException; -import java.util.Vector; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.util.Wait; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -public class DurableSubProcessMultiRestartTest { - - private static final Logger LOG = LoggerFactory.getLogger(DurableSubProcessMultiRestartTest.class); - - public static final long RUNTIME = 1 * 60 * 1000; - - private BrokerService broker; - private ActiveMQTopic topic; - - private final ReentrantReadWriteLock processLock = new ReentrantReadWriteLock(true); - - private int restartCount = 0; - private final int SUBSCRIPTION_ID = 1; - - static final Vector exceptions = new Vector<>(); - - /** - * The test creates a durable subscriber and producer with a broker that is - * continually restarted. - * - * Producer creates a message every .5 seconds -creates a new connection for - * each message - * - * durable subscriber - comes online for 10 seconds, - then goes offline for - * a "moment" - repeats the cycle - * - * approx every 10 seconds the broker restarts. Subscriber and Producer - * connections will be closed BEFORE the restart. - * - * The Durable subscriber is "unsubscribed" before the the end of the test. - * - * checks for number of kahaDB files left on filesystem. - * - * @throws Exception - */ - @Test - public void testProcess() throws Exception { - - DurableSubscriber durableSubscriber = new DurableSubscriber(SUBSCRIPTION_ID); - MsgProducer msgProducer = new MsgProducer(); - - try { - // register the subscription & start messages - durableSubscriber.start(); - msgProducer.start(); - - long endTime = System.currentTimeMillis() + RUNTIME; - - while (endTime > System.currentTimeMillis()) { - Thread.sleep(10000); - restartBroker(); - } - } catch (Throwable e) { - exit("ProcessTest.testProcess failed.", e); - } - - // wait for threads to finish - try { - msgProducer.join(); - durableSubscriber.join(); - } catch (InterruptedException e) { - e.printStackTrace(System.out); - } - - // restart broker one last time - restartBroker(); - - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - - final KahaDBPersistenceAdapter pa = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - assertTrue("only less than two journal files should be left: " + pa.getStore().getJournal().getFileMap().size(), Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - return pa.getStore().getJournal().getFileMap().size() <= 2; - } - }, TimeUnit.MINUTES.toMillis(3))); - - LOG.info("DONE."); - } - - private void restartBroker() throws Exception { - LOG.info("Broker restart: waiting for components."); - - processLock.writeLock().lock(); - try { - destroyBroker(); - startBroker(false); - - restartCount++; - LOG.info("Broker restarted. count: " + restartCount); - } finally { - processLock.writeLock().unlock(); - } - } - - /** - * Producers messages - */ - final class MsgProducer extends Thread { - - String url = "vm://" + DurableSubProcessMultiRestartTest.getName(); - - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - - private long msgCount; - int messageRover = 0; - - public MsgProducer() { - super("MsgProducer"); - setDaemon(true); - } - - @Override - public void run() { - - long endTime = RUNTIME + System.currentTimeMillis(); - - try { - while (endTime > System.currentTimeMillis()) { - - Thread.sleep(500); - - processLock.readLock().lock(); - try { - send(); - } finally { - processLock.readLock().unlock(); - } - LOG.info("MsgProducer msgCount=" + msgCount); - } - } catch (Throwable e) { - exit("Server.run failed", e); - } - } - - public void send() throws JMSException { - - LOG.info("Sending ... "); - - Connection con = cf.createConnection(); - - Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageProducer prod = sess.createProducer(null); - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setBooleanProperty("COMMIT", true); - prod.send(topic, message); - - msgCount++; - LOG.info("Message Sent."); - - sess.close(); - con.close(); - } - } - - /** - * Consumes massages from a durable subscription. Goes online/offline - * periodically. - */ - private final class DurableSubscriber extends Thread { - - String url = "tcp://localhost:61656"; - - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - - public static final String SUBSCRIPTION_NAME = "subscription"; - - private final int id; - private final String conClientId; - private long msgCount; - - public DurableSubscriber(int id) throws JMSException { - super("DurableSubscriber" + id); - setDaemon(true); - - this.id = id; - conClientId = "cli" + id; - - subscribe(); - } - - @Override - public void run() { - - long end = System.currentTimeMillis() + RUNTIME; - - try { - - // while (true) { - while (end > System.currentTimeMillis()) { - - processLock.readLock().lock(); - try { - process(5000); - } finally { - processLock.readLock().unlock(); - } - } - - unsubscribe(); - - } catch (JMSException maybe) { - if (maybe.getCause() instanceof IOException) { - // ok on broker shutdown; - } else { - exit(toString() + " failed with JMSException", maybe); - } - } catch (Throwable e) { - exit(toString() + " failed.", e); - } - - LOG.info(toString() + " DONE. MsgCout=" + msgCount); - } - - private void process(long duration) throws JMSException { - LOG.info(toString() + " ONLINE."); - - Connection con = openConnection(); - Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageConsumer consumer = sess.createDurableSubscriber(topic, SUBSCRIPTION_NAME); - - long end = System.currentTimeMillis() + duration; - - try { - while (end > System.currentTimeMillis()) { - Message message = consumer.receive(100); - if (message != null) { - LOG.info(toString() + "received message..."); - msgCount++; - } - } - } finally { - sess.close(); - con.close(); - LOG.info(toString() + " OFFLINE."); - } - } - - private Connection openConnection() throws JMSException { - Connection con = cf.createConnection(); - con.setClientID(conClientId); - con.start(); - return con; - } - - private void subscribe() throws JMSException { - Connection con = openConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - - session.createDurableSubscriber(topic, SUBSCRIPTION_NAME); - LOG.info(toString() + " SUBSCRIBED"); - - session.close(); - con.close(); - } - - private void unsubscribe() throws JMSException { - Connection con = openConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.unsubscribe(SUBSCRIPTION_NAME); - LOG.info(toString() + " UNSUBSCRIBED"); - - session.close(); - con.close(); - } - - @Override - public String toString() { - return "DurableSubscriber[id=" + id + "]"; - } - } - - // -------- helper methods ----------- - - public static void exit(String message) { - exit(message, null); - } - - public static void exit(String message, Throwable e) { - Throwable cause = new RuntimeException(message, e); - LOG.error(message, cause); - exceptions.add(cause); - fail(cause.toString()); - } - - @Before - public void setUp() throws Exception { - topic = new ActiveMQTopic("TopicT"); - startBroker(); - } - - @After - public void tearDown() throws Exception { - destroyBroker(); - } - - private void startBroker() throws Exception { - startBroker(true); - } - - private void startBroker(boolean deleteAllMessages) throws Exception { - if (broker != null) - return; - - broker = BrokerFactory.createBroker("broker:(vm://" + getName() + ")"); - broker.setBrokerName(getName()); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - - broker.setKeepDurableSubsActive(true); - - File kahadbData = new File("activemq-data/" + getName() + "-kahadb"); - if (deleteAllMessages) - delete(kahadbData); - - broker.setPersistent(true); - KahaDBPersistenceAdapter kahadb = new KahaDBPersistenceAdapter(); - kahadb.setDirectory(kahadbData); - kahadb.setJournalMaxFileLength(20 * 1024); - broker.setPersistenceAdapter(kahadb); - - broker.addConnector("tcp://localhost:61656"); - - broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getTempUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getStoreUsage().setLimit(256 * 1024 * 1024); - - broker.start(); - } - - protected static String getName() { - return "DurableSubProcessMultiRestartTest"; - } - - private static boolean delete(File path) { - if (path == null) - return true; - - if (path.isDirectory()) { - for (File file : path.listFiles()) { - delete(file); - } - } - return path.delete(); - } - - private void destroyBroker() throws Exception { - if (broker == null) - return; - - broker.stop(); - broker = null; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessTest.java deleted file mode 100644 index cb99e1fd44..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessTest.java +++ /dev/null @@ -1,678 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.io.File; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashSet; -import java.util.Vector; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.CopyOnWriteArrayList; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -// see https://issues.apache.org/activemq/browse/AMQ-2985 -// this demonstrated receiving old messages eventually along with validating order receipt -public class DurableSubProcessTest extends org.apache.activemq.TestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(DurableSubProcessTest.class); - public static final long RUNTIME = 4 * 60 * 1000; - - public static final int SERVER_SLEEP = 2 * 1000; // max - public static final int CARGO_SIZE = 10; // max - - public static final int MAX_CLIENTS = 7; - public static final Random CLIENT_LIFETIME = new Random(30 * 1000, 2 * 60 * 1000); - public static final Random CLIENT_ONLINE = new Random(2 * 1000, 15 * 1000); - public static final Random CLIENT_OFFLINE = new Random(1 * 1000, 20 * 1000); - - public static final boolean PERSISTENT_BROKER = true; - public static final boolean ALLOW_SUBSCRIPTION_ABANDONMENT = true; - - private BrokerService broker; - private ActiveMQTopic topic; - - private ClientManager clientManager; - private Server server; - private HouseKeeper houseKeeper; - - static final Vector exceptions = new Vector<>(); - - @Test - public void testProcess() { - try { - server.start(); - clientManager.start(); - - if (ALLOW_SUBSCRIPTION_ABANDONMENT) - houseKeeper.start(); - - Thread.sleep(RUNTIME); - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - } catch (Throwable e) { - exit("DurableSubProcessTest.testProcess failed.", e); - } - LOG.info("DONE."); - } - - /** - * Creates batch of messages in a transaction periodically. - * The last message in the transaction is always a special - * message what contains info about the whole transaction. - *

Notifies the clients about the created messages also. - */ - final class Server extends Thread { - - final String url = "vm://" + DurableSubProcessTest.this.getName() + "?" + - "jms.redeliveryPolicy.maximumRedeliveries=2&jms.redeliveryPolicy.initialRedeliveryDelay=500&" + - "jms.producerWindowSize=20971520&jms.prefetchPolicy.all=100&" + - "jms.copyMessageOnSend=false&jms.disableTimeStampsByDefault=false&" + - "jms.alwaysSyncSend=true&jms.dispatchAsync=false&" + - "jms.watchTopicAdvisories=false&" + - "waitForStart=200&create=false"; - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - - final Object sendMutex = new Object(); - final String[] cargos = new String[500]; - - int transRover = 0; - int messageRover = 0; - - public Server() { - super("Server"); - setDaemon(true); - } - - @Override - public void run() { - try { - while (true) { - DurableSubProcessTest.sleepRandom(SERVER_SLEEP); - send(); - } - } catch (Throwable e) { - exit("Server.run failed", e); - } - } - - public void send() throws JMSException { - // do not create new clients now - // ToDo: Test this case later. - synchronized (sendMutex) { - int trans = ++transRover; - boolean relevantTrans = random(2) > 1; - ClientType clientType = relevantTrans ? ClientType.randomClientType() : null; // sends this types - int count = random(200); - - LOG.info("Sending Trans[id=" + trans + ", count=" + count + ", clientType=" + clientType + "]"); - - Connection con = cf.createConnection(); - Session sess = con.createSession(true, Session.AUTO_ACKNOWLEDGE); - MessageProducer prod = sess.createProducer(null); - - for (int i = 0; i < count; i++) { - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - String type = clientType != null ? clientType.randomMessageType() : ClientType.randomNonRelevantMessageType(); - message.setStringProperty("TYPE", type); - - if (CARGO_SIZE > 0) - message.setStringProperty("CARGO", getCargo(CARGO_SIZE)); - - prod.send(topic, message); - clientManager.onServerMessage(message); - } - - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setIntProperty("TRANS", trans); - message.setBooleanProperty("COMMIT", true); - message.setBooleanProperty("RELEVANT", relevantTrans); - prod.send(topic, message); - clientManager.onServerMessage(message); - - sess.commit(); - sess.close(); - con.close(); - } - } - - private String getCargo(int length) { - if (length == 0) - return null; - - if (length < cargos.length) { - String result = cargos[length]; - if (result == null) { - result = getCargoImpl(length); - cargos[length] = result; - } - return result; - } - return getCargoImpl(length); - } - - private String getCargoImpl(int length) { - StringBuilder sb = new StringBuilder(length); - for (int i = length; --i >= 0; ) { - sb.append('a'); - } - return sb.toString(); - } - } - - /** - * Clients listen on different messages in the topic. - * The 'TYPE' property helps the client to select the - * proper messages. - */ - private enum ClientType { - A("a", "b", "c"), - B("c", "d", "e"), - C("d", "e", "f"), - D("g", "h"); - - public final String[] messageTypes; - public final HashSet messageTypeSet; - public final String selector; - - ClientType(String... messageTypes) { - this.messageTypes = messageTypes; - messageTypeSet = new HashSet<>(Arrays.asList(messageTypes)); - - StringBuilder sb = new StringBuilder("TYPE in ("); - for (int i = 0; i < messageTypes.length; i++) { - if (i > 0) - sb.append(", "); - sb.append('\'').append(messageTypes[i]).append('\''); - } - sb.append(')'); - selector = sb.toString(); - } - - public static ClientType randomClientType() { - return values()[DurableSubProcessTest.random(values().length - 1)]; - } - - public final String randomMessageType() { - return messageTypes[DurableSubProcessTest.random(messageTypes.length - 1)]; - } - - public static String randomNonRelevantMessageType() { - return Integer.toString(DurableSubProcessTest.random(20)); - } - - public final boolean isRelevant(String messageType) { - return messageTypeSet.contains(messageType); - } - - @Override - public final String toString() { - return this.name() /*+ '[' + selector + ']'*/; - } - } - - /** - * Creates new cliens. - */ - private final class ClientManager extends Thread { - - private int clientRover = 0; - - private final CopyOnWriteArrayList clients = new CopyOnWriteArrayList<>(); - - public ClientManager() { - super("ClientManager"); - setDaemon(true); - } - - @Override - public void run() { - try { - while (true) { - if (clients.size() < MAX_CLIENTS) - createNewClient(); - - int size = clients.size(); - sleepRandom(size * 3 * 1000, size * 6 * 1000); - } - } catch (Throwable e) { - exit("ClientManager.run failed.", e); - } - } - - private void createNewClient() throws JMSException { - ClientType type = ClientType.randomClientType(); - - Client client; - synchronized (server.sendMutex) { - client = new Client(++clientRover, type, CLIENT_LIFETIME, CLIENT_ONLINE, CLIENT_OFFLINE); - clients.add(client); - } - client.start(); - - LOG.info(client.toString() + " created. " + this); - } - - public void removeClient(Client client) { - clients.remove(client); - } - - public void onServerMessage(Message message) throws JMSException { - for (Client client : clients) { - client.onServerMessage(message); - } - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("ClientManager[count="); - sb.append(clients.size()); - sb.append(", clients="); - boolean sep = false; - for (Client client : clients) { - if (sep) - sb.append(", "); - else - sep = true; - sb.append(client.toString()); - } - sb.append(']'); - return sb.toString(); - } - } - - /** - * Consumes massages from a durable subscription. - * Goes online/offline periodically. Checks the incoming messages - * against the sent messages of the server. - */ - private final class Client extends Thread { - - String url = "failover:(tcp://localhost:61656?wireFormat.maxInactivityDuration=0)?" + - "jms.watchTopicAdvisories=false&" + - "jms.alwaysSyncSend=true&jms.dispatchAsync=true&" + - "jms.producerWindowSize=20971520&" + - "jms.copyMessageOnSend=false&" + - "initialReconnectDelay=100&maxReconnectDelay=30000&" + - "useExponentialBackOff=true"; - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - - public static final String SUBSCRIPTION_NAME = "subscription"; - - private final int id; - private final String conClientId; - - private final Random lifetime; - private final Random online; - private final Random offline; - - private final ClientType clientType; - private final String selector; - - private final ConcurrentLinkedQueue waitingList = new ConcurrentLinkedQueue<>(); - - public Client(int id, ClientType clientType, Random lifetime, Random online, Random offline) throws JMSException { - super("Client" + id); - setDaemon(true); - - this.id = id; - conClientId = "cli" + id; - this.clientType = clientType; - selector = "(COMMIT = true and RELEVANT = true) or " + clientType.selector; - - this.lifetime = lifetime; - this.online = online; - this.offline = offline; - - subscribe(); - } - - @Override - public void run() { - long end = System.currentTimeMillis() + lifetime.next(); - try { - boolean sleep = false; - while (true) { - long max = end - System.currentTimeMillis(); - if (max <= 0) - break; - - if (sleep) - offline.sleepRandom(); - else - sleep = true; - - process(online.next()); - } - - if (!ALLOW_SUBSCRIPTION_ABANDONMENT || random(1) > 0) - unsubscribe(); - else { - LOG.info("Client abandon the subscription. " + this); - - // housekeeper should sweep these abandoned subscriptions - houseKeeper.abandonedSubscriptions.add(conClientId); - } - } catch (Throwable e) { - exit(toString() + " failed.", e); - } - - clientManager.removeClient(this); - LOG.info(toString() + " DONE."); - } - - private void process(long millis) throws JMSException { - long end = System.currentTimeMillis() + millis; - long hardEnd = end + 2000; // wait to finish the transaction. - boolean inTransaction = false; - int transCount = 0; - - LOG.info(toString() + " ONLINE."); - Connection con = openConnection(); - Session sess = con.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = sess.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, false); - try { - do { - long max = end - System.currentTimeMillis(); - if (max <= 0) { - if (!inTransaction) - break; - - max = hardEnd - System.currentTimeMillis(); - if (max <= 0) - exit("" + this + " failed: Transaction is not finished."); - } - - Message message = consumer.receive(max); - if (message == null) - continue; - - onClientMessage(message); - - if (message.propertyExists("COMMIT")) { - message.acknowledge(); - - LOG.info("Received Trans[id=" + message.getIntProperty("TRANS") + ", count=" + transCount + "] in " + this + "."); - - inTransaction = false; - transCount = 0; - } else { - inTransaction = true; - transCount++; - } - } while (true); - } finally { - sess.close(); - con.close(); - - LOG.info(toString() + " OFFLINE."); - - // Check if the messages are in the waiting - // list for long time. - Message topMessage = waitingList.peek(); - if (topMessage != null) - checkDeliveryTime(topMessage); - } - } - - public void onServerMessage(Message message) throws JMSException { - if (Boolean.TRUE.equals(message.getObjectProperty("COMMIT"))) { - if (Boolean.TRUE.equals(message.getObjectProperty("RELEVANT"))) - waitingList.add(message); - } else { - String messageType = message.getStringProperty("TYPE"); - if (clientType.isRelevant(messageType)) - waitingList.add(message); - } - } - - public void onClientMessage(Message message) { - Message serverMessage = waitingList.poll(); - try { - if (serverMessage == null) - exit("" + this + " failed: There is no next server message, but received: " + message); - - Integer receivedId = (Integer) message.getObjectProperty("ID"); - Integer serverId = (Integer) serverMessage.getObjectProperty("ID"); - if (receivedId == null || serverId == null) - exit("" + this + " failed: message ID not found.\r\n" + - " received: " + message + "\r\n" + - " server: " + serverMessage); - - if (!serverId.equals(receivedId)) - exit("" + this + " failed: Received wrong message.\r\n" + - " received: " + message + "\r\n" + - " server: " + serverMessage); - - checkDeliveryTime(message); - } catch (Throwable e) { - exit("" + this + ".onClientMessage failed.\r\n" + - " received: " + message + "\r\n" + - " server: " + serverMessage, e); - } - } - - /** - * Checks if the message was not delivered fast enough. - */ - public void checkDeliveryTime(Message message) throws JMSException { - long creation = message.getJMSTimestamp(); - long min = System.currentTimeMillis() - (offline.max + online.min); - - if (min > creation) { - SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss.SSS"); - exit("" + this + ".checkDeliveryTime failed. Message time: " + df.format(new Date(creation)) + ", min: " + df.format(new Date(min)) + "\r\n" + message); - } - } - - private Connection openConnection() throws JMSException { - Connection con = cf.createConnection(); - con.setClientID(conClientId); - con.start(); - return con; - } - - private void subscribe() throws JMSException { - Connection con = openConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, true); - session.close(); - con.close(); - } - - private void unsubscribe() throws JMSException { - Connection con = openConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.unsubscribe(SUBSCRIPTION_NAME); - session.close(); - con.close(); - } - - @Override - public String toString() { - return "Client[id=" + id + ", type=" + clientType + "]"; - } - } - - /** - * Sweeps out not-used durable subscriptions. - */ - private final class HouseKeeper extends Thread { - - private HouseKeeper() { - super("HouseKeeper"); - setDaemon(true); - } - - public final CopyOnWriteArrayList abandonedSubscriptions = new CopyOnWriteArrayList<>(); - - @Override - public void run() { - while (true) { - try { - Thread.sleep(60 * 1000); - sweep(); - } catch (InterruptedException ex) { - break; - } catch (Throwable e) { - Exception log = new Exception("HouseKeeper failed.", e); - log.printStackTrace(); - } - } - } - - private void sweep() throws Exception { - LOG.info("Housekeeper sweeping."); - - int closed = 0; - ArrayList sweeped = new ArrayList<>(); - try { - for (String clientId : abandonedSubscriptions) { - sweeped.add(clientId); - LOG.info("Sweeping out subscription of " + clientId + "."); - broker.getAdminView().destroyDurableSubscriber(clientId, Client.SUBSCRIPTION_NAME); - closed++; - } - } finally { - abandonedSubscriptions.removeAll(sweeped); - } - - LOG.info("Housekeeper sweeped out " + closed + " subscriptions."); - } - } - - public static int random(int max) { - return (int) (Math.random() * (max + 1)); - } - - public static int random(int min, int max) { - return random(max - min) + min; - } - - public static void sleepRandom(int maxMillis) throws InterruptedException { - Thread.sleep(random(maxMillis)); - } - - public static void sleepRandom(int minMillis, int maxMillis) throws InterruptedException { - Thread.sleep(random(minMillis, maxMillis)); - } - - public static final class Random { - - final int min; - final int max; - - Random(int min, int max) { - this.min = min; - this.max = max; - } - - public int next() { - return random(min, max); - } - - public void sleepRandom() throws InterruptedException { - DurableSubProcessTest.sleepRandom(min, max); - } - } - - public static void exit(String message) { - exit(message, null); - } - - public static void exit(String message, Throwable e) { - Throwable log = new RuntimeException(message, e); - log.printStackTrace(); - LOG.error(message, e); - exceptions.add(e); - fail(message); - } - - @Override - protected void setUp() throws Exception { - topic = (ActiveMQTopic) createDestination(); - startBroker(); - - clientManager = new ClientManager(); - server = new Server(); - houseKeeper = new HouseKeeper(); - - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - - destroyBroker(); - } - - private void startBroker() throws Exception { - startBroker(true); - } - - private void startBroker(boolean deleteAllMessages) throws Exception { - if (broker != null) - return; - - broker = BrokerFactory.createBroker("broker:(vm://localhost)"); - broker.setBrokerName(getName()); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - - if (PERSISTENT_BROKER) { - broker.setPersistent(true); - KahaDBPersistenceAdapter persistenceAdapter = new KahaDBPersistenceAdapter(); - persistenceAdapter.setDirectory(new File("activemq-data/" + getName())); - broker.setPersistenceAdapter(persistenceAdapter); - } else - broker.setPersistent(false); - - broker.addConnector("tcp://localhost:61656"); - - broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getTempUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getStoreUsage().setLimit(256 * 1024 * 1024); - - broker.start(); - } - - private void destroyBroker() throws Exception { - if (broker == null) - return; - - broker.stop(); - broker = null; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessWithRestartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessWithRestartTest.java deleted file mode 100644 index da9afb0a1f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubProcessWithRestartTest.java +++ /dev/null @@ -1,776 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR ONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.io.File; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashSet; -import java.util.Vector; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.leveldb.LevelDBStore; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -public class DurableSubProcessWithRestartTest { - - private static final Logger LOG = LoggerFactory.getLogger(DurableSubProcessWithRestartTest.class); - public static final long RUNTIME = 5 * 60 * 1000; - - public static final int SERVER_SLEEP = 2 * 1000; // max - public static final int CARGO_SIZE = 400; // max - - public static final int MAX_CLIENTS = 5; - public static final Random CLIENT_LIFETIME = new Random(5 * 1000, 2 * 5 * 1000); - public static final Random CLIENT_ONLINE = new Random(2 * 1000, 2 * 1000); - public static final Random CLIENT_OFFLINE = new Random(10 * 1000, 10 * 1000); - - public static final Persistence PERSISTENT_ADAPTER = Persistence.KAHADB; - public static final long BROKER_RESTART = 1 * 10 * 1000; - - public static final boolean ALLOW_SUBSCRIPTION_ABANDONMENT = true; - public static final boolean CHECK_REDELIVERY = true; - - private BrokerService broker; - private ActiveMQTopic topic; - - private ClientManager clientManager; - private Server server; - private HouseKeeper houseKeeper; - - private final ReentrantReadWriteLock processLock = new ReentrantReadWriteLock(true); - private int restartCount = 0; - static final Vector exceptions = new Vector<>(); - - // this is a nice test but it takes 5mins, may be handy in the future - // resulting bug https://issues.apache.org/jira/browse/AMQ-3190 - @Ignore("covered by org.apache.activemq.usecases.DurableSubscriptionOfflineTest.testNoMissOnMatchingSubAfterRestart()") - @Test - public void testProcess() { - try { - server.start(); - clientManager.start(); - - if (ALLOW_SUBSCRIPTION_ABANDONMENT) - houseKeeper.start(); - - long end = System.currentTimeMillis() + RUNTIME; - - while (true) { - long now = System.currentTimeMillis(); - if (now > end) - break; - - now = end - now; - now = now < BROKER_RESTART ? now : BROKER_RESTART; - Thread.sleep(now); - - restartBroker(); - } - } catch (Throwable e) { - exit("ProcessTest.testProcess failed.", e); - } - - processLock.writeLock().lock(); - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - LOG.info("DONE."); - } - - private void restartBroker() throws Exception { - LOG.info("Broker restart: waiting for components."); - - processLock.writeLock().lock(); - try { - destroyBroker(); - startBroker(false); - - restartCount++; - LOG.info("Broker restarted. count: " + restartCount); - } finally { - processLock.writeLock().unlock(); - } - } - - /** - * Creates batch of messages in a transaction periodically. The last message - * in the transaction is always a special message what contains info about - * the whole transaction. - *

- * Notifies the clients about the created messages also. - */ - final class Server extends Thread { - - final String url = "vm://" + DurableSubProcessWithRestartTest.getName() + "?" + "jms.redeliveryPolicy.maximumRedeliveries=2&jms.redeliveryPolicy.initialRedeliveryDelay=500&" + "jms.producerWindowSize=20971520&jms.prefetchPolicy.all=100&" + "jms.copyMessageOnSend=false&jms.disableTimeStampsByDefault=false&" + "jms.alwaysSyncSend=true&jms.dispatchAsync=false&" + "jms.watchTopicAdvisories=false&" + "waitForStart=200&create=false"; - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - - final Object sendMutex = new Object(); - final String[] cargos = new String[500]; - - int transRover = 0; - int messageRover = 0; - - public Server() { - super("Server"); - setDaemon(true); - } - - @Override - public void run() { - try { - while (true) { - DurableSubProcessWithRestartTest.sleepRandom(SERVER_SLEEP); - - processLock.readLock().lock(); - try { - send(); - } finally { - processLock.readLock().unlock(); - } - } - } catch (Throwable e) { - exit("Server.run failed", e); - } - } - - public void send() throws JMSException { - // do not create new clients now - // ToDo: Test this case later. - synchronized (sendMutex) { - int trans = ++transRover; - boolean relevantTrans = random(2) > 1; - ClientType clientType = relevantTrans ? ClientType.randomClientType() : null; // sends this types - int count = random(200); - - LOG.info("Sending Trans[id=" + trans + ", count=" + count + ", clientType=" + clientType + "]"); - - Connection con = cf.createConnection(); - Session sess = con.createSession(true, Session.SESSION_TRANSACTED); - MessageProducer prod = sess.createProducer(null); - - for (int i = 0; i < count; i++) { - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setIntProperty("TRANS", trans); - String type = clientType != null ? clientType.randomMessageType() : ClientType.randomNonRelevantMessageType(); - message.setStringProperty("TYPE", type); - - if (CARGO_SIZE > 0) - message.setStringProperty("CARGO", getCargo(random(CARGO_SIZE))); - - prod.send(topic, message); - clientManager.onServerMessage(message); - } - - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setIntProperty("TRANS", trans); - message.setBooleanProperty("COMMIT", true); - message.setBooleanProperty("RELEVANT", relevantTrans); - prod.send(topic, message); - clientManager.onServerMessage(message); - - sess.commit(); - LOG.info("Committed Trans[id=" + trans + ", count=" + count + ", clientType=" + clientType + "], ID=" + messageRover); - - sess.close(); - con.close(); - } - } - - private String getCargo(int length) { - if (length == 0) - return null; - - if (length < cargos.length) { - String result = cargos[length]; - if (result == null) { - result = getCargoImpl(length); - cargos[length] = result; - } - return result; - } - return getCargoImpl(length); - } - - private String getCargoImpl(int length) { - StringBuilder sb = new StringBuilder(length); - for (int i = length; --i >= 0; ) { - sb.append('a'); - } - return sb.toString(); - } - } - - /** - * Clients listen on different messages in the topic. The 'TYPE' property - * helps the client to select the proper messages. - */ - private enum ClientType { - A("a", "b", "c"), B("c", "d", "e"), C("d", "e", "f"), D("g", "h"); - - public final String[] messageTypes; - public final HashSet messageTypeSet; - public final String selector; - - ClientType(String... messageTypes) { - this.messageTypes = messageTypes; - messageTypeSet = new HashSet<>(Arrays.asList(messageTypes)); - - StringBuilder sb = new StringBuilder("TYPE in ("); - for (int i = 0; i < messageTypes.length; i++) { - if (i > 0) - sb.append(", "); - sb.append('\'').append(messageTypes[i]).append('\''); - } - sb.append(')'); - selector = sb.toString(); - } - - public static ClientType randomClientType() { - return values()[DurableSubProcessWithRestartTest.random(values().length - 1)]; - } - - public final String randomMessageType() { - return messageTypes[DurableSubProcessWithRestartTest.random(messageTypes.length - 1)]; - } - - public static String randomNonRelevantMessageType() { - return Integer.toString(DurableSubProcessWithRestartTest.random(20)); - } - - public final boolean isRelevant(String messageType) { - return messageTypeSet.contains(messageType); - } - - @Override - public final String toString() { - return this.name() /* + '[' + selector + ']' */; - } - } - - /** - * Creates new cliens. - */ - private final class ClientManager extends Thread { - - private int clientRover = 0; - - private final CopyOnWriteArrayList clients = new CopyOnWriteArrayList<>(); - - public ClientManager() { - super("ClientManager"); - setDaemon(true); - } - - @Override - public void run() { - try { - while (true) { - if (clients.size() < MAX_CLIENTS) { - processLock.readLock().lock(); - try { - createNewClient(); - } finally { - processLock.readLock().unlock(); - } - } - - int size = clients.size(); - sleepRandom(size * 3 * 1000, size * 6 * 1000); - } - } catch (Throwable e) { - exit("ClientManager.run failed.", e); - } - } - - private void createNewClient() throws JMSException { - ClientType type = ClientType.randomClientType(); - - Client client; - synchronized (server.sendMutex) { - client = new Client(++clientRover, type, CLIENT_LIFETIME, CLIENT_ONLINE, CLIENT_OFFLINE); - clients.add(client); - } - client.start(); - - LOG.info(client.toString() + " created. " + this); - } - - public void removeClient(Client client) { - clients.remove(client); - } - - public void onServerMessage(Message message) throws JMSException { - for (Client client : clients) { - client.onServerMessage(message); - } - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("ClientManager[count="); - sb.append(clients.size()); - sb.append(", clients="); - boolean sep = false; - for (Client client : clients) { - if (sep) - sb.append(", "); - else - sep = true; - sb.append(client.toString()); - } - sb.append(']'); - return sb.toString(); - } - } - - /** - * Consumes massages from a durable subscription. Goes online/offline - * periodically. Checks the incoming messages against the sent messages of - * the server. - */ - private final class Client extends Thread { - - String url = "failover:(tcp://localhost:61656?wireFormat.maxInactivityDuration=0)?" + "jms.watchTopicAdvisories=false&" + "jms.alwaysSyncSend=true&jms.dispatchAsync=true&" + "jms.producerWindowSize=20971520&" + "jms.copyMessageOnSend=false&" + "initialReconnectDelay=100&maxReconnectDelay=30000&" + "useExponentialBackOff=true"; - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - - public static final String SUBSCRIPTION_NAME = "subscription"; - - private final int id; - private final String conClientId; - - private final Random lifetime; - private final Random online; - private final Random offline; - - private final ClientType clientType; - private final String selector; - - private final ConcurrentLinkedQueue waitingList = new ConcurrentLinkedQueue<>(); - private final HashSet processed = CHECK_REDELIVERY ? new HashSet(10000) : null; - - public Client(int id, ClientType clientType, Random lifetime, Random online, Random offline) throws JMSException { - super("Client" + id); - setDaemon(true); - - this.id = id; - conClientId = "cli" + id; - this.clientType = clientType; - selector = "(COMMIT = true and RELEVANT = true) or " + clientType.selector; - - this.lifetime = lifetime; - this.online = online; - this.offline = offline; - - subscribe(); - } - - @Override - public void run() { - long end = System.currentTimeMillis() + lifetime.next(); - try { - boolean sleep = false; - while (true) { - long max = end - System.currentTimeMillis(); - if (max <= 0) - break; - - if (sleep) - offline.sleepRandom(); - else - sleep = true; - - processLock.readLock().lock(); - try { - process(online.next()); - } finally { - processLock.readLock().unlock(); - } - } - - if (!ALLOW_SUBSCRIPTION_ABANDONMENT || random(1) > 0) - unsubscribe(); - else { - LOG.info("Client abandon the subscription. " + this); - - // housekeeper should sweep these abandoned subscriptions - houseKeeper.abandonedSubscriptions.add(conClientId); - } - } catch (Throwable e) { - exit(toString() + " failed.", e); - } - - clientManager.removeClient(this); - LOG.info(toString() + " DONE."); - } - - private void process(long millis) throws JMSException { - long end = System.currentTimeMillis() + millis; - long hardEnd = end + 20000; // wait to finish the transaction. - boolean inTransaction = false; - int transCount = 0; - - LOG.info(toString() + " ONLINE."); - Connection con = openConnection(); - Session sess = con.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = sess.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, false); - try { - do { - long max = end - System.currentTimeMillis(); - if (max <= 0) { - if (!inTransaction) - break; - - max = hardEnd - System.currentTimeMillis(); - if (max <= 0) - exit("" + this + " failed: Transaction is not finished."); - } - - Message message = consumer.receive(max); - if (message == null) - continue; - - onClientMessage(message); - - if (message.propertyExists("COMMIT")) { - message.acknowledge(); // CLIENT_ACKNOWLEDGE - - LOG.info("Received Trans[id=" + message.getIntProperty("TRANS") + ", count=" + transCount + "] in " + this + "."); - - inTransaction = false; - transCount = 0; - } else { - inTransaction = true; - transCount++; - } - } while (true); - } finally { - sess.close(); - con.close(); - - LOG.info(toString() + " OFFLINE."); - - // Check if the messages are in the waiting - // list for long time. - Message topMessage = waitingList.peek(); - if (topMessage != null) - checkDeliveryTime(topMessage); - } - } - - public void onServerMessage(Message message) throws JMSException { - if (Boolean.TRUE.equals(message.getObjectProperty("COMMIT"))) { - if (Boolean.TRUE.equals(message.getObjectProperty("RELEVANT"))) - waitingList.add(message); - } else { - String messageType = message.getStringProperty("TYPE"); - if (clientType.isRelevant(messageType)) - waitingList.add(message); - } - } - - public void onClientMessage(Message message) { - Message serverMessage = waitingList.poll(); - try { - Integer receivedId = (Integer) message.getObjectProperty("ID"); - if (processed != null && processed.contains(receivedId)) - LOG.info("! Message has been processed before. " + this + " message = " + message); - - if (serverMessage == null) - exit("" + this + " failed: There is no next server message, but received: " + message); - - Integer serverId = (Integer) serverMessage.getObjectProperty("ID"); - if (receivedId == null || serverId == null) - exit("" + this + " failed: message ID not found.\r\n" + " received: " + message + "\r\n" + " server: " + serverMessage); - - if (!serverId.equals(receivedId)) { - String detail = processed != null ? Arrays.toString(processed.toArray()) + "\n" : ""; - exit(detail + this + " failed: Received wrong message.\r\n" + " received: " + message + "\r\n" + " server: " + serverMessage); - } - - checkDeliveryTime(message); - - if (processed != null) - processed.add(receivedId); - } catch (Throwable e) { - exit("" + this + ".onClientMessage failed.\r\n" + " received: " + message + "\r\n" + " server: " + serverMessage, e); - } - } - - /** - * Checks if the message was not delivered fast enough. - */ - @SuppressWarnings("unused") - public void checkDeliveryTime(Message message) throws JMSException { - long creation = message.getJMSTimestamp(); - long min = System.currentTimeMillis() - (offline.max + online.min) * (BROKER_RESTART > 0 ? 4 : 1); - - if (false && min > creation) { - SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss.SSS"); - exit("" + this + ".checkDeliveryTime failed. Message time: " + df.format(new Date(creation)) + ", min: " + df.format(new Date(min)) + "\r\n" + message); - } - } - - private Connection openConnection() throws JMSException { - Connection con = cf.createConnection(); - con.setClientID(conClientId); - con.start(); - return con; - } - - private void subscribe() throws JMSException { - Connection con = openConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, true); - session.close(); - con.close(); - } - - private void unsubscribe() throws JMSException { - Connection con = openConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.unsubscribe(SUBSCRIPTION_NAME); - session.close(); - con.close(); - } - - @Override - public String toString() { - return "Client[id=" + id + ", type=" + clientType + "]"; - } - } - - /** - * Sweeps out not-used durable subscriptions. - */ - private final class HouseKeeper extends Thread { - - private HouseKeeper() { - super("HouseKeeper"); - setDaemon(true); - } - - public final CopyOnWriteArrayList abandonedSubscriptions = new CopyOnWriteArrayList<>(); - - @Override - public void run() { - while (true) { - try { - Thread.sleep(3 * 60 * 1000); - - processLock.readLock().lock(); - try { - sweep(); - } finally { - processLock.readLock().unlock(); - } - } catch (InterruptedException ex) { - break; - } catch (Throwable e) { - Exception log = new Exception("HouseKeeper failed.", e); - log.printStackTrace(); - } - } - } - - private void sweep() throws Exception { - LOG.info("Housekeeper sweeping."); - - int closed = 0; - ArrayList sweeped = new ArrayList<>(); - try { - for (String clientId : abandonedSubscriptions) { - LOG.info("Sweeping out subscription of " + clientId + "."); - broker.getAdminView().destroyDurableSubscriber(clientId, Client.SUBSCRIPTION_NAME); - sweeped.add(clientId); - closed++; - } - } catch (Exception ignored) { - LOG.info("Ex on destroy sub " + ignored); - } finally { - abandonedSubscriptions.removeAll(sweeped); - } - - LOG.info("Housekeeper sweeped out " + closed + " subscriptions."); - } - } - - public static int random(int max) { - return (int) (Math.random() * (max + 1)); - } - - public static int random(int min, int max) { - return random(max - min) + min; - } - - public static void sleepRandom(int maxMillis) throws InterruptedException { - Thread.sleep(random(maxMillis)); - } - - public static void sleepRandom(int minMillis, int maxMillis) throws InterruptedException { - Thread.sleep(random(minMillis, maxMillis)); - } - - public static final class Random { - - final int min; - final int max; - - Random(int min, int max) { - this.min = min; - this.max = max; - } - - public int next() { - return random(min, max); - } - - public void sleepRandom() throws InterruptedException { - DurableSubProcessWithRestartTest.sleepRandom(min, max); - } - } - - public static void exit(String message) { - exit(message, null); - } - - public static void exit(String message, Throwable e) { - Throwable cause = new RuntimeException(message, e); - LOG.error(message, cause); - exceptions.add(cause); - fail(cause.toString()); - } - - @Before - public void setUp() throws Exception { - topic = new ActiveMQTopic("TopicT"); - startBroker(); - - clientManager = new ClientManager(); - server = new Server(); - houseKeeper = new HouseKeeper(); - - } - - @After - public void tearDown() throws Exception { - destroyBroker(); - } - - private enum Persistence { - MEMORY, LEVELDB, KAHADB - } - - private void startBroker() throws Exception { - startBroker(true); - } - - private void startBroker(boolean deleteAllMessages) throws Exception { - if (broker != null) - return; - - broker = BrokerFactory.createBroker("broker:(vm://" + getName() + ")"); - broker.setBrokerName(getName()); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - - switch (PERSISTENT_ADAPTER) { - case MEMORY: - broker.setPersistent(false); - break; - - case LEVELDB: - File datadir = new File("activemq-data/" + getName() + "-leveldb"); - if (deleteAllMessages) - delete(datadir); - - broker.setPersistent(true); - LevelDBStore amq = new LevelDBStore(); - amq.setDirectory(datadir); - broker.setPersistenceAdapter(amq); - break; - - case KAHADB: - File kahadbData = new File("activemq-data/" + getName() + "-kahadb"); - if (deleteAllMessages) - delete(kahadbData); - - broker.setPersistent(true); - KahaDBPersistenceAdapter kahadb = new KahaDBPersistenceAdapter(); - kahadb.setDirectory(kahadbData); - kahadb.setJournalMaxFileLength(5 * 1024 * 1024); - broker.setPersistenceAdapter(kahadb); - break; - } - - broker.addConnector("tcp://localhost:61656"); - - broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getTempUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getStoreUsage().setLimit(256 * 1024 * 1024); - - broker.start(); - } - - protected static String getName() { - return "DurableSubProcessWithRestartTest"; - } - - private static boolean delete(File path) { - if (path == null) - return true; - - if (path.isDirectory()) { - for (File file : path.listFiles()) { - delete(file); - } - } - return path.delete(); - } - - private void destroyBroker() throws Exception { - if (broker == null) - return; - - broker.stop(); - broker = null; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubSelectorDelayTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubSelectorDelayTest.java deleted file mode 100644 index f1f591a416..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubSelectorDelayTest.java +++ /dev/null @@ -1,308 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR ONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.io.File; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.util.Wait; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertTrue; - -public class DurableSubSelectorDelayTest { - - private static final Logger LOG = LoggerFactory.getLogger(DurableSubSelectorDelayTest.class); - - public static final long RUNTIME = 3 * 60 * 1000; - - private BrokerService broker; - private ActiveMQTopic topic; - private String connectionUri; - - @Test - public void testProcess() throws Exception { - - MsgProducer msgProducer = new MsgProducer(); - msgProducer.start(); - - DurableSubscriber subscribers[] = new DurableSubscriber[10]; - - for (int i = 0; i < subscribers.length; i++) { - subscribers[i] = new DurableSubscriber(i); - subscribers[i].process(); - } - - // wait for server to finish - msgProducer.join(); - - for (int j = 0; j < subscribers.length; j++) { - LOG.info("Unsubscribing subscriber " + subscribers[j]); - subscribers[j].unsubscribe(); - } - - // allow the clean up thread time to run - TimeUnit.MINUTES.sleep(2); - - final KahaDBPersistenceAdapter pa = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - assertTrue("less than two journal file should be left, was: " + pa.getStore().getJournal().getFileMap().size(), Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - return pa.getStore().getJournal().getFileMap().size() <= 2; - } - }, TimeUnit.MINUTES.toMillis(2))); - - LOG.info("DONE."); - } - - /** - * Message Producer - */ - final class MsgProducer extends Thread { - - final String url = "vm://" + DurableSubSelectorDelayTest.getName(); - - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - - int transRover = 0; - int messageRover = 0; - int count = 40; - - public MsgProducer() { - super("MsgProducer"); - setDaemon(true); - } - - public MsgProducer(int count) { - super("MsgProducer"); - setDaemon(true); - this.count = count; - } - - @Override - public void run() { - long endTime = RUNTIME + System.currentTimeMillis(); - - try { - while (endTime > System.currentTimeMillis()) { - Thread.sleep(400); - send(); - } - } catch (Throwable e) { - e.printStackTrace(System.out); - throw new RuntimeException(e); - } - } - - public void send() throws JMSException { - - int trans = ++transRover; - boolean relevantTrans = true; - - LOG.info("Sending Trans[id=" + trans + ", count=" + count + "]"); - - Connection con = cf.createConnection(); - - Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageProducer prod = sess.createProducer(null); - - for (int i = 0; i < count; i++) { - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setIntProperty("TRANS", trans); - message.setBooleanProperty("RELEVANT", false); - prod.send(topic, message); - } - - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setIntProperty("TRANS", trans); - message.setBooleanProperty("COMMIT", true); - message.setBooleanProperty("RELEVANT", relevantTrans); - prod.send(topic, message); - - LOG.info("Committed Trans[id=" + trans + ", count=" + count + "], ID=" + messageRover); - - sess.close(); - con.close(); - } - } - - /** - * Consumes massages from a durable subscription. Goes online/offline - * periodically. Checks the incoming messages against the sent messages of - * the server. - */ - private final class DurableSubscriber { - - final ConnectionFactory cf = new ActiveMQConnectionFactory(connectionUri); - - private final String subName; - - private final int id; - private final String conClientId; - private final String selector; - - public DurableSubscriber(int id) throws JMSException { - this.id = id; - conClientId = "cli" + id; - subName = "subscription" + id; - selector = "RELEVANT = true"; - } - - private void process() throws JMSException { - long end = System.currentTimeMillis() + 20000; - int transCount = 0; - - LOG.info(toString() + " ONLINE."); - Connection con = openConnection(); - - Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = sess.createDurableSubscriber(topic, subName, selector, false); - - try { - - do { - long max = end - System.currentTimeMillis(); - - if (max <= 0) { - break; - } - - Message message = consumer.receive(max); - if (message == null) { - continue; - } - - LOG.info("Received Trans[id=" + message.getIntProperty("TRANS") + ", count=" + transCount + "] in " + this + "."); - - } while (true); - - } finally { - sess.close(); - con.close(); - - LOG.info(toString() + " OFFLINE."); - } - } - - private Connection openConnection() throws JMSException { - Connection con = cf.createConnection(); - con.setClientID(conClientId); - con.start(); - return con; - } - - private void unsubscribe() throws JMSException { - Connection con = openConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.unsubscribe(subName); - session.close(); - con.close(); - } - - @Override - public String toString() { - return "DurableSubscriber[id=" + id + "]"; - } - } - - @Before - public void setUp() throws Exception { - topic = new ActiveMQTopic("TopicT"); - startBroker(); - } - - @After - public void tearDown() throws Exception { - destroyBroker(); - } - - private void startBroker() throws Exception { - startBroker(true); - } - - private void startBroker(boolean deleteAllMessages) throws Exception { - if (broker != null) - return; - - broker = BrokerFactory.createBroker("broker:(vm://" + getName() + ")"); - broker.setBrokerName(getName()); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - - File kahadbData = new File("activemq-data/" + getName() + "-kahadb"); - if (deleteAllMessages) - delete(kahadbData); - - broker.setPersistent(true); - KahaDBPersistenceAdapter kahadb = new KahaDBPersistenceAdapter(); - kahadb.setDirectory(kahadbData); - kahadb.setJournalMaxFileLength(500 * 1024); - broker.setPersistenceAdapter(kahadb); - - connectionUri = broker.addConnector("tcp://localhost:0").getPublishableConnectString(); - - broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getTempUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getStoreUsage().setLimit(256 * 1024 * 1024); - - broker.start(); - } - - protected static String getName() { - return "DurableSubSelectorDelayTest"; - } - - private static boolean delete(File path) { - if (path == null) - return true; - - if (path.isDirectory()) { - for (File file : path.listFiles()) { - delete(file); - } - } - return path.delete(); - } - - private void destroyBroker() throws Exception { - if (broker == null) - return; - - broker.stop(); - broker = null; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubSelectorDelayWithRestartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubSelectorDelayWithRestartTest.java deleted file mode 100644 index 13bcedae25..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubSelectorDelayWithRestartTest.java +++ /dev/null @@ -1,337 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR ONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.io.File; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.util.Wait; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertTrue; - -public class DurableSubSelectorDelayWithRestartTest { - - private static final Logger LOG = LoggerFactory.getLogger(DurableSubSelectorDelayWithRestartTest.class); - - public static final long RUNTIME = 1 * 60 * 1000; - - private boolean RESTART = true; - private int NUMBER_SUBSCRIBERS = 3; - - private BrokerService broker; - private ActiveMQTopic topic; - - @Test - public void testProcess() throws Exception { - - MsgProducer msgProducer = new MsgProducer(); - msgProducer.start(); - - DurableSubscriber subscribers[] = new DurableSubscriber[NUMBER_SUBSCRIBERS]; - - for (int i = 0; i < subscribers.length - 1; i++) { - subscribers[i] = new DurableSubscriber(i); - subscribers[i].process(); - } - - // wait for server to finish - msgProducer.join(); - - //for the last subscriber pop one message into the topic. - subscribers[(subscribers.length - 1)] = new DurableSubscriber((subscribers.length - 1)); - subscribers[(subscribers.length - 1)].subscribe(); - MsgProducer msgProducer2 = new MsgProducer(); - msgProducer2.send(); - subscribers[(subscribers.length - 1)].process(); - - // unsubscribe all, but the last subscriber. - for (int j = 0; j < (subscribers.length - 1); j++) { - LOG.info("Unsubscribing subscriber " + subscribers[j]); - subscribers[j].unsubscribe(); - } - - final KahaDBPersistenceAdapter pa = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - assertTrue("small number of journal files should be left ", Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - LOG.info("journal data file count - expected {} actual {}", 4, pa.getStore().getJournal().getFileMap().size()); - return pa.getStore().getJournal().getFileMap().size() < 4; - } - }, TimeUnit.MINUTES.toMillis(3))); - - LOG.info("DONE."); - } - - /** - * Message Producer - */ - final class MsgProducer extends Thread { - - final String url = "failover:(tcp://localhost:61656)"; - - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - - int transRover = 0; - int messageRover = 0; - - public MsgProducer() { - super("MsgProducer"); - setDaemon(true); - } - - @Override - public void run() { - long endTime = RUNTIME + System.currentTimeMillis(); - - try { - while (endTime > System.currentTimeMillis()) { - Thread.sleep(400); - send(); - - //restart broker all the time - if (RESTART) { - destroyBroker(); - startBroker(false); - } - } - } catch (Throwable e) { - e.printStackTrace(System.out); - throw new RuntimeException(e); - } - } - - public void send() throws JMSException { - - int trans = ++transRover; - boolean relevantTrans = true; - int count = 40; - - LOG.info("Sending Trans[id=" + trans + ", count=" + count + "]"); - - Connection con = cf.createConnection(); - - Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageProducer prod = sess.createProducer(null); - - for (int i = 0; i < count; i++) { - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setIntProperty("TRANS", trans); - message.setBooleanProperty("RELEVANT", false); - prod.send(topic, message); - } - - Message message = sess.createMessage(); - message.setIntProperty("ID", ++messageRover); - message.setIntProperty("TRANS", trans); - message.setBooleanProperty("COMMIT", true); - message.setBooleanProperty("RELEVANT", relevantTrans); - prod.send(topic, message); - - LOG.info("Committed Trans[id=" + trans + ", count=" + count + "], ID=" + messageRover); - - sess.close(); - con.close(); - } - } - - /** - * Consumes massages from a durable subscription. Goes online/offline - * periodically. Checks the incoming messages against the sent messages of - * the server. - */ - private final class DurableSubscriber { - - final String url = "failover:(tcp://localhost:61656)"; - - final ConnectionFactory cf = new ActiveMQConnectionFactory(url); - - private final String subName; - - private final int id; - private final String conClientId; - private final String selector; - - public DurableSubscriber(int id) throws JMSException { - this.id = id; - conClientId = "cli" + id; - subName = "subscription" + id; - selector = "RELEVANT = true"; - } - - private void process() throws JMSException { - long end = System.currentTimeMillis() + 20000; - int transCount = 0; - - LOG.info(toString() + " ONLINE."); - Connection con = openConnection(); - - Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = sess.createDurableSubscriber(topic, subName, selector, false); - - try { - - do { - long max = end - System.currentTimeMillis(); - - if (max <= 0) { - break; - } - - Message message = consumer.receive(max); - if (message == null) { - continue; - } - - LOG.info("Received Trans[id=" + message.getIntProperty("TRANS") + ", count=" + transCount + "] in " + this + "."); - - } while (true); - - } finally { - try { - sess.close(); - con.close(); - } catch (Exception e) { - } - - LOG.info(toString() + " OFFLINE."); - } - } - - private Connection openConnection() throws JMSException { - Connection con = cf.createConnection(); - con.setClientID(conClientId); - con.start(); - return con; - } - - public void subscribe() throws JMSException { - LOG.info(toString() + "SUBSCRIBING"); - Connection con = openConnection(); - - Session sess = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - sess.createDurableSubscriber(topic, subName, selector, false); - - sess.close(); - con.close(); - } - - private void unsubscribe() throws JMSException { - Connection con = openConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.unsubscribe(subName); - session.close(); - con.close(); - } - - @Override - public String toString() { - return "DurableSubscriber[id=" + id + "]"; - } - } - - @Before - public void setUp() throws Exception { - topic = new ActiveMQTopic("TopicT"); - startBroker(); - } - - @After - public void tearDown() throws Exception { - destroyBroker(); - } - - private void startBroker() throws Exception { - startBroker(true); - } - - private void startBroker(boolean deleteAllMessages) throws Exception { - if (broker != null) - return; - - broker = BrokerFactory.createBroker("broker:(vm://" + getName() + ")"); - broker.setBrokerName(getName()); - broker.setAdvisorySupport(false); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - - File kahadbData = new File("activemq-data/" + getName() + "-kahadb"); - if (deleteAllMessages) - delete(kahadbData); - - broker.setPersistent(true); - KahaDBPersistenceAdapter kahadb = new KahaDBPersistenceAdapter(); - kahadb.setDirectory(kahadbData); - kahadb.setJournalMaxFileLength(10 * 1024); - kahadb.setCleanupInterval(5000); - broker.setPersistenceAdapter(kahadb); - - broker.addConnector("tcp://localhost:61656"); - - broker.getSystemUsage().getMemoryUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getTempUsage().setLimit(256 * 1024 * 1024); - broker.getSystemUsage().getStoreUsage().setLimit(256 * 1024 * 1024); - - LOG.info(toString() + "Starting Broker..."); - broker.start(); - broker.waitUntilStarted(); - - LOG.info(toString() + " Broker started!!"); - } - - protected static String getName() { - return "DurableSubSelectorDelayTest"; - } - - private static boolean delete(File path) { - if (path == null) - return true; - - if (path.isDirectory()) { - for (File file : path.listFiles()) { - delete(file); - } - } - return path.delete(); - } - - private void destroyBroker() throws Exception { - if (broker == null) - return; - - broker.stop(); - broker = null; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubsOfflineSelectorConcurrentConsumeIndexUseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubsOfflineSelectorConcurrentConsumeIndexUseTest.java deleted file mode 100644 index 0b158fa56e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubsOfflineSelectorConcurrentConsumeIndexUseTest.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.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import junit.framework.Test; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.store.PersistenceAdapter; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.store.kahadb.KahaDBStore; -import org.apache.activemq.util.Wait; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DurableSubsOfflineSelectorConcurrentConsumeIndexUseTest extends org.apache.activemq.TestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(DurableSubsOfflineSelectorConcurrentConsumeIndexUseTest.class); - public int messageCount = 10000; - private BrokerService broker; - private ActiveMQTopic topic; - private final List exceptions = new ArrayList<>(); - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + getName(true)); - connectionFactory.setWatchTopicAdvisories(false); - return connectionFactory; - } - - @Override - protected Connection createConnection() throws Exception { - return createConnection("id"); - } - - protected Connection createConnection(String name) throws Exception { - Connection con = getConnectionFactory().createConnection(); - con.setClientID(name); - con.start(); - return con; - } - - public static Test suite() { - return suite(DurableSubsOfflineSelectorConcurrentConsumeIndexUseTest.class); - } - - @Override - protected void setUp() throws Exception { - exceptions.clear(); - topic = (ActiveMQTopic) createDestination(); - createBroker(); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - destroyBroker(); - } - - private void createBroker() throws Exception { - createBroker(true); - } - - private void createBroker(boolean deleteAllMessages) throws Exception { - broker = BrokerFactory.createBroker("broker:(vm://" + getName(true) + ")"); - broker.setBrokerName(getName(true)); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - broker.getManagementContext().setCreateConnector(false); - broker.setAdvisorySupport(false); - broker.addConnector("tcp://0.0.0.0:0"); - - setDefaultPersistenceAdapter(broker); - - ((KahaDBPersistenceAdapter) broker.getPersistenceAdapter()).getStore().getPageFile().setPageSize(1024); - - broker.start(); - } - - private void destroyBroker() throws Exception { - if (broker != null) - broker.stop(); - } - - public void testIndexPageUsage() throws Exception { - Connection con = createConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "true", "filter = 'true'", true); - session.close(); - - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "false", "filter = 'false'", true); - session.close(); - - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "all", null, true); - session.close(); - - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "all2", null, true); - session.close(); - - con.close(); - - // send messages - - final CountDownLatch goOn = new CountDownLatch(1); - Thread sendThread = new Thread() { - @Override - public void run() { - try { - - final Connection sendCon = createConnection("send"); - final Session sendSession = sendCon.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageProducer producer = sendSession.createProducer(null); - - for (int i = 0; i < messageCount; i++) { - boolean filter = i % 2 == 1; - Message message = sendSession.createMessage(); - message.setStringProperty("filter", filter ? "true" : "false"); - producer.send(topic, message); - - if (i > 0 && i % 10000 == 0) { - LOG.info("Sent:" + i); - } - if (i > messageCount / 2) { - goOn.countDown(); - } - } - sendSession.close(); - sendCon.close(); - } catch (Exception e) { - exceptions.add(e); - } - } - }; - sendThread.start(); - - goOn.await(5, TimeUnit.MINUTES); - LOG.info("Activating consumers"); - - // consume messages in parallel - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageConsumer consumerTrue = session.createDurableSubscriber(topic, "true", "filter = 'true'", true); - Listener listenerT = new Listener(); - consumerTrue.setMessageListener(listenerT); - - MessageConsumer consumerFalse = session.createDurableSubscriber(topic, "false", "filter = 'false'", true); - Listener listenerF = new Listener(); - consumerFalse.setMessageListener(listenerF); - - MessageConsumer consumerAll = session.createDurableSubscriber(topic, "all", null, true); - Listener listenerA = new Listener(); - consumerAll.setMessageListener(listenerA); - - MessageConsumer consumerAll2 = session.createDurableSubscriber(topic, "all2", null, true); - Listener listenerA2 = new Listener(); - consumerAll2.setMessageListener(listenerA2); - - waitFor(listenerA, messageCount); - assertEquals(messageCount, listenerA.count); - - waitFor(listenerA2, messageCount); - assertEquals(messageCount, listenerA2.count); - - assertEquals(messageCount / 2, listenerT.count); - assertEquals(messageCount / 2, listenerF.count); - - consumerTrue.close(); - session.unsubscribe("true"); - - consumerFalse.close(); - session.unsubscribe("false"); - - consumerAll.close(); - session.unsubscribe("all"); - - session.close(); - con.close(); - - PersistenceAdapter persistenceAdapter = broker.getPersistenceAdapter(); - if (persistenceAdapter instanceof KahaDBPersistenceAdapter) { - final KahaDBStore store = ((KahaDBPersistenceAdapter) persistenceAdapter).getStore(); - LOG.info("Store page count: " + store.getPageFile().getPageCount()); - LOG.info("Store free page count: " + store.getPageFile().getFreePageCount()); - LOG.info("Store page in-use: " + (store.getPageFile().getPageCount() - store.getPageFile().getFreePageCount())); - - assertTrue("no leak of pages, always use just 11", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 11 == store.getPageFile().getPageCount() - store.getPageFile().getFreePageCount(); - } - }, TimeUnit.SECONDS.toMillis(10))); - } - } - - private void waitFor(final Listener listener, final int count) throws Exception { - - assertTrue("got all messages on time", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return listener.count == count; - } - }, TimeUnit.MINUTES.toMillis(10))); - - } - - public static class Listener implements MessageListener { - - int count = 0; - String id = null; - - Listener() { - } - - @Override - public void onMessage(Message message) { - count++; - if (id != null) { - try { - LOG.info(id + ", " + message.getJMSMessageID()); - } catch (Exception ignored) { - } - } - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubsOfflineSelectorIndexUseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubsOfflineSelectorIndexUseTest.java deleted file mode 100644 index ab3d70975e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubsOfflineSelectorIndexUseTest.java +++ /dev/null @@ -1,232 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import junit.framework.Test; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.store.PersistenceAdapter; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.store.kahadb.KahaDBStore; -import org.apache.activemq.util.Wait; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DurableSubsOfflineSelectorIndexUseTest extends org.apache.activemq.TestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(DurableSubsOfflineSelectorIndexUseTest.class); - public int messageCount = 400; - private BrokerService broker; - private ActiveMQTopic topic; - private List exceptions = new ArrayList<>(); - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + getName(true)); - connectionFactory.setWatchTopicAdvisories(false); - return connectionFactory; - } - - @Override - protected Connection createConnection() throws Exception { - return createConnection("id"); - } - - protected Connection createConnection(String name) throws Exception { - Connection con = super.createConnection(); - con.setClientID(name); - con.start(); - return con; - } - - public static Test suite() { - return suite(DurableSubsOfflineSelectorIndexUseTest.class); - } - - @Override - protected void setUp() throws Exception { - exceptions.clear(); - topic = (ActiveMQTopic) createDestination(); - createBroker(); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - destroyBroker(); - } - - private void createBroker() throws Exception { - createBroker(true); - } - - private void createBroker(boolean deleteAllMessages) throws Exception { - broker = BrokerFactory.createBroker("broker:(vm://" + getName(true) + ")"); - broker.setBrokerName(getName(true)); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - broker.getManagementContext().setCreateConnector(false); - broker.setAdvisorySupport(false); - broker.addConnector("tcp://0.0.0.0:0"); - - setDefaultPersistenceAdapter(broker); - broker.start(); - } - - private void destroyBroker() throws Exception { - if (broker != null) - broker.stop(); - } - - public void initCombosForTestIndexPageUsage() { - addCombinationValues("messageCount", new Integer[]{890, 900, 400}); - } - - public void testIndexPageUsage() throws Exception { - Connection con = createConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "true", "filter = 'true'", true); - session.close(); - - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "false", "filter = 'false'", true); - session.close(); - - con.close(); - - // send messages - final Connection sendCon = createConnection("send"); - final Session sendSession = sendCon.createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageProducer producer = sendSession.createProducer(null); - - Thread sendThread = new Thread() { - @Override - public void run() { - try { - - for (int i = 0; i < messageCount; i++) { - boolean filter = i % 2 == 1; - Message message = sendSession.createMessage(); - message.setStringProperty("filter", filter ? "true" : "false"); - producer.send(topic, message); - - if (i > 0 && i % 1000 == 0) { - LOG.info("Sent:" + i); - } - } - sendSession.close(); - sendCon.close(); - } catch (Exception e) { - exceptions.add(e); - } - } - }; - sendThread.start(); - - sendThread.join(); - - // settle with sent messages - TimeUnit.SECONDS.sleep(4); - - // consume messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageConsumer consumerTrue = session.createDurableSubscriber(topic, "true", "filter = 'true'", true); - Listener listenerT = new Listener(); - consumerTrue.setMessageListener(listenerT); - - waitFor(listenerT, messageCount / 2); - - MessageConsumer consumerFalse = session.createDurableSubscriber(topic, "false", "filter = 'false'", true); - Listener listenerF = new Listener(); - consumerFalse.setMessageListener(listenerF); - - waitFor(listenerF, messageCount / 2); - - assertEquals(messageCount / 2, listenerT.count); - assertEquals(messageCount / 2, listenerF.count); - - consumerTrue.close(); - session.unsubscribe("true"); - - consumerFalse.close(); - session.unsubscribe("false"); - - session.close(); - con.close(); - - PersistenceAdapter persistenceAdapter = broker.getPersistenceAdapter(); - if (persistenceAdapter instanceof KahaDBPersistenceAdapter) { - final KahaDBStore store = ((KahaDBPersistenceAdapter) persistenceAdapter).getStore(); - LOG.info("Store page count: " + store.getPageFile().getPageCount()); - LOG.info("Store free page count: " + store.getPageFile().getFreePageCount()); - LOG.info("Store page in-use: " + (store.getPageFile().getPageCount() - store.getPageFile().getFreePageCount())); - - assertTrue("no leak of pages, always use just 10", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 10 == store.getPageFile().getPageCount() - store.getPageFile().getFreePageCount(); - } - }, TimeUnit.SECONDS.toMillis(10))); - } - } - - private void waitFor(final Listener listener, final int count) throws Exception { - - assertTrue("got all messages on time", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return listener.count == count; - } - }, TimeUnit.MINUTES.toMillis(10))); - - } - - public static class Listener implements MessageListener { - - int count = 0; - String id = null; - - Listener() { - } - - @Override - public void onMessage(Message message) { - count++; - if (id != null) { - try { - LOG.info(id + ", " + message.getJMSMessageID()); - } catch (Exception ignored) { - } - } - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberNonPersistentMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberNonPersistentMessageTest.java deleted file mode 100644 index 3f7cc7b327..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberNonPersistentMessageTest.java +++ /dev/null @@ -1,320 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.jms.Topic; -import javax.management.MBeanServer; -import javax.management.ObjectName; -import java.io.File; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.io.Writer; -import java.lang.management.ManagementFactory; -import java.util.Date; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.store.kahadb.KahaDBStore; -import org.apache.activemq.util.Wait; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DurableSubscriberNonPersistentMessageTest extends TestCase { - - private final Logger LOG = LoggerFactory.getLogger(DurableSubscriberNonPersistentMessageTest.class); - private String brokerURL; - private String consumerBrokerURL; - - int initialMaxMsgs = 10; - int cleanupMsgCount = 10; - int totalMsgCount = initialMaxMsgs + cleanupMsgCount; - int totalMsgReceived = 0; - int sleep = 500; - int reconnectSleep = 2000; - int messageTimeout = 1000; - int messageSize = 1024; - - // Note: If ttl is set 0, the default set by the broker will be used if any - // setting a value greater than 0 will enable the producer to set the ttl on - // the message - long ttl = 0; - - static String clientId = "Jason"; - MBeanServer mbeanServer; - - BrokerService broker; - - @Override - protected void setUp() throws Exception { - super.setUp(); - broker = new BrokerService(); - TransportConnector transportConnector = broker.addConnector("tcp://localhost:0"); - KahaDBStore store = new KahaDBStore(); - store.setDirectory(new File("data")); - broker.setPersistenceAdapter(store); - broker.start(); - - brokerURL = "failover:(" + transportConnector.getPublishableConnectString() + ")"; - consumerBrokerURL = brokerURL + "?jms.prefetchPolicy.all=100"; - - mbeanServer = ManagementFactory.getPlatformMBeanServer(); - } - - @Override - protected void tearDown() throws Exception { - broker.stop(); - super.tearDown(); - } - - /** - * Create the test case - * - * @param testName name of the test case - */ - public DurableSubscriberNonPersistentMessageTest(String testName) { - super(testName); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() { - return new TestSuite(DurableSubscriberNonPersistentMessageTest.class); - } - - public void testDurableSubscriberNonPersistentMessage() { - String interest = "TEST"; - - LOG.info("Starting DurableSubscriberNonPersistentMessageTest"); - - try { - // create durable topic consumer and disconnect - createConsumer(interest, 0); - Thread.sleep(1000); - - // produce 15 messages to topic - Producer producer = new Producer(brokerURL, interest, messageSize, ttl); - producer.sendMessages(totalMsgCount); - producer.close(); - LOG.info(totalMsgCount + " messages sent"); - - // durable topic consumer will consume 10 messages and disconnect - createConsumer(interest, initialMaxMsgs); - - Thread.sleep(reconnectSleep); - - createConsumer(interest, cleanupMsgCount); - - String brokerVersion = (String) mbeanServer.getAttribute(new ObjectName("org.apache.activemq:brokerName=localhost,type=Broker"), "BrokerVersion"); - - LOG.info("Test run on: " + brokerVersion); - final String theJmxObject = "org.apache.activemq:type=Broker,brokerName=localhost," + - "endpoint=Consumer,destinationType=Topic,destinationName=TEST,clientId=Jason," + - "consumerId=Durable(Jason_MyDurableTopic)"; - - assertTrue("pendingQueueSize should be zero", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Integer pendingQueueSize = (Integer) mbeanServer.getAttribute(new ObjectName(theJmxObject), "PendingQueueSize"); - LOG.info("pendingQueueSize = " + pendingQueueSize); - return pendingQueueSize.intValue() == 0; - } - })); - - assertTrue("cursorMemoryUsage should be zero", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Long cursorMemoryUsage = (Long) mbeanServer.getAttribute(new ObjectName(theJmxObject), "CursorMemoryUsage"); - LOG.info("cursorMemoryUsage = " + cursorMemoryUsage); - return cursorMemoryUsage.longValue() == 0L; - } - })); - - // Not sure what the behavior should be here, if the messages - // expired the received count shouldn't equal total message count - assertTrue(totalMsgReceived == initialMaxMsgs + cleanupMsgCount); - } catch (Exception e) { - LOG.error("Exception Executing DurableSubscriberNonPersistentMessageTest: " + getStackTrace(e)); - fail("Should not throw any exceptions"); - } - } - - // create durable topic consumer and max number of messages - public void createConsumer(String interest, int maxMsgs) { - int messageReceived = 0; - int messagesNotReceived = 0; - - LOG.info("Starting DurableSubscriber"); - - Consumer consumer = null; - - try { - consumer = new Consumer(consumerBrokerURL, interest, clientId); - - for (int i = 0; i < maxMsgs; i++) { - try { - Message msg = consumer.getMessage(messageTimeout); - if (msg != null) { - LOG.debug("Received Message: " + msg.toString()); - messageReceived++; - totalMsgReceived++; - } else { - LOG.debug("message " + i + " not received"); - messagesNotReceived++; - } - - Thread.sleep(sleep); - } catch (InterruptedException ie) { - LOG.debug("Exception: " + ie); - } - } - - consumer.close(); - - LOG.info("Consumer Finished"); - LOG.info("Received " + messageReceived); - LOG.info("Not Received " + messagesNotReceived); - } catch (JMSException e) { - LOG.error("Exception Executing SimpleConsumer: " + getStackTrace(e)); - } - } - - public String getStackTrace(Throwable aThrowable) { - final Writer result = new StringWriter(); - final PrintWriter printWriter = new PrintWriter(result); - aThrowable.printStackTrace(printWriter); - return result.toString(); - } - - public class Producer { - - protected ConnectionFactory factory; - protected transient Connection connection; - protected transient Session session; - protected transient MessageProducer producer; - protected static final int messageSize = 1024; - - public Producer(String brokerURL, String interest, int messageSize, long ttl) throws JMSException { - - factory = new ActiveMQConnectionFactory(brokerURL); - connection = factory.createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(session.createTopic(interest)); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - if (ttl > 0) { - producer.setTimeToLive(ttl); - } - } - - public void close() throws JMSException { - if (connection != null) { - connection.close(); - } - } - - protected void sendMessage() throws JMSException { - TextMessage textMessage = session.createTextMessage("test message"); - producer.send(textMessage); - } - - protected void sendMessages(int count) throws JMSException { - for (int i = 0; i < count; i++) { - TextMessage textMessage = session.createTextMessage(createMessageText(i)); - producer.send(textMessage); - } - } - - private String createMessageText(int index) { - StringBuffer buffer = new StringBuffer(messageSize); - buffer.append("Message: " + index + " sent at: " + new Date()); - if (buffer.length() > messageSize) { - return buffer.substring(0, messageSize); - } - for (int i = buffer.length(); i < messageSize; i++) { - buffer.append(' '); - } - return buffer.toString(); - } - - protected void commitTransaction() throws JMSException { - session.commit(); - } - } - - public class Consumer { - - private final ConnectionFactory factory; - private final ActiveMQConnection connection; - private final Session session; - private final MessageConsumer messageConsumer; - - public Consumer(String brokerURL, String interest, String clientId) throws JMSException { - factory = new ActiveMQConnectionFactory(brokerURL); - connection = (ActiveMQConnection) factory.createConnection(); - connection.setClientID(clientId); - connection.start(); - connection.getPrefetchPolicy().setAll(15); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createTopic(interest); - messageConsumer = session.createDurableSubscriber((Topic) destination, "MyDurableTopic"); - } - - public void deleteAllMessages() throws JMSException { - while (getMessage(500) != null) { - // empty queue - } - } - - public Message getMessage(int timeout) throws JMSException { - return messageConsumer.receive(timeout); - } - - public void close() throws JMSException { - if (messageConsumer != null) { - messageConsumer.close(); - } - if (session != null) { - session.close(); - } - if (connection != null) { - connection.close(); - } - } - - public Session getSession() { - return session; - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberWithNetworkDisconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberWithNetworkDisconnectTest.java deleted file mode 100644 index aec944918d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberWithNetworkDisconnectTest.java +++ /dev/null @@ -1,243 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.net.URI; -import java.util.List; - -import junit.framework.Test; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.network.DiscoveryNetworkConnector; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.util.SocketProxy; -import org.apache.activemq.util.Wait; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class DurableSubscriberWithNetworkDisconnectTest extends JmsMultipleBrokersTestSupport { - - private static final Log LOG = LogFactory.getLog(DurableSubscriberWithNetworkDisconnectTest.class); - private static final int NETWORK_DOWN_TIME = 10000; - private static final String HUB = "HubBroker"; - private static final String SPOKE = "SpokeBroker"; - private SocketProxy socketProxy; - private long networkDownTimeStart; - private long inactiveDuration = 1000; - private long receivedMsgs = 0; - private boolean useSocketProxy = true; - protected static final int MESSAGE_COUNT = 200; - public boolean useDuplexNetworkBridge = true; - public boolean simulateStalledNetwork; - public boolean dynamicOnly = true; - public long networkTTL = 3; - public boolean exponentialBackOff; - public boolean failover = false; - public boolean inactivity = true; - - public void initCombosForTestSendOnAReceiveOnBWithTransportDisconnect() { - addCombinationValues("failover", new Object[]{Boolean.FALSE, Boolean.TRUE}); - } - - public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception { - bridgeBrokers(SPOKE, HUB); - - startAllBrokers(); - - // Setup connection - URI hubURI = brokers.get(HUB).broker.getVmConnectorURI(); - URI spokeURI = brokers.get(SPOKE).broker.getVmConnectorURI(); - ActiveMQConnectionFactory facHub = new ActiveMQConnectionFactory(hubURI); - ActiveMQConnectionFactory facSpoke = new ActiveMQConnectionFactory(spokeURI); - Connection conHub = facHub.createConnection(); - Connection conSpoke = facSpoke.createConnection(); - conHub.setClientID("clientHUB"); - conSpoke.setClientID("clientSPOKE"); - conHub.start(); - conSpoke.start(); - Session sesHub = conHub.createSession(false, Session.AUTO_ACKNOWLEDGE); - Session sesSpoke = conSpoke.createSession(false, Session.AUTO_ACKNOWLEDGE); - - ActiveMQTopic topic = new ActiveMQTopic("TEST.FOO"); - String consumerName = "consumerName"; - - // Setup consumers - MessageConsumer remoteConsumer = sesSpoke.createDurableSubscriber(topic, consumerName); - remoteConsumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message msg) { - try { - TextMessage textMsg = (TextMessage) msg; - receivedMsgs++; - LOG.info("Received messages (" + receivedMsgs + "): " + textMsg.getText()); - } catch (JMSException e) { - e.printStackTrace(); - } - } - }); - - // allow subscription information to flow back to Spoke - sleep(1000); - - // Setup producer - MessageProducer localProducer = sesHub.createProducer(topic); - localProducer.setDeliveryMode(DeliveryMode.PERSISTENT); - - // Send messages - for (int i = 0; i < MESSAGE_COUNT; i++) { - sleep(50); - if (i == 50 || i == 150) { - if (simulateStalledNetwork) { - socketProxy.pause(); - } else { - socketProxy.close(); - } - networkDownTimeStart = System.currentTimeMillis(); - } else if (networkDownTimeStart > 0) { - // restart after NETWORK_DOWN_TIME seconds - sleep(NETWORK_DOWN_TIME); - networkDownTimeStart = 0; - if (simulateStalledNetwork) { - socketProxy.goOn(); - } else { - socketProxy.reopen(); - } - } else { - // slow message production to allow bridge to recover and limit message duplication - sleep(500); - } - Message test = sesHub.createTextMessage("test-" + i); - localProducer.send(test); - } - - LOG.info("waiting for messages to flow"); - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return receivedMsgs >= MESSAGE_COUNT; - } - }); - - assertTrue("At least message " + MESSAGE_COUNT + - " must be received, count=" + receivedMsgs, MESSAGE_COUNT <= receivedMsgs); - brokers.get(HUB).broker.deleteAllMessages(); - brokers.get(SPOKE).broker.deleteAllMessages(); - conHub.close(); - conSpoke.close(); - } - - @Override - protected void startAllBrokers() throws Exception { - // Ensure HUB is started first so bridge will be active from the get go - BrokerItem brokerItem = brokers.get(HUB); - brokerItem.broker.start(); - brokerItem = brokers.get(SPOKE); - brokerItem.broker.start(); - sleep(600); - } - - @Override - public void setUp() throws Exception { - networkDownTimeStart = 0; - inactiveDuration = 1000; - useSocketProxy = true; - receivedMsgs = 0; - super.setAutoFail(true); - super.setUp(); - final String options = "?persistent=true&useJmx=false&deleteAllMessagesOnStartup=true"; - createBroker(new URI("broker:(tcp://localhost:61617)/" + HUB + options)); - createBroker(new URI("broker:(tcp://localhost:61616)/" + SPOKE + options)); - } - - @Override - public void tearDown() throws Exception { - super.tearDown(); - if (socketProxy != null) { - socketProxy.close(); - } - } - - public static Test suite() { - return suite(DurableSubscriberWithNetworkDisconnectTest.class); - } - - private void sleep(int milliSecondTime) { - try { - Thread.sleep(milliSecondTime); - } catch (InterruptedException igonred) { - } - } - - @Override - protected NetworkConnector bridgeBrokers(BrokerService localBroker, - BrokerService remoteBroker, - boolean l_dynamicOnly, - int networkTTL, - boolean l_conduit, - boolean l_failover) throws Exception { - List transportConnectors = remoteBroker.getTransportConnectors(); - URI remoteURI; - if (!transportConnectors.isEmpty()) { - remoteURI = transportConnectors.get(0).getConnectUri(); - if (useSocketProxy) { - socketProxy = new SocketProxy(remoteURI); - remoteURI = socketProxy.getUrl(); - } - String options = ""; - if (failover) { - options = "static:(failover:(" + remoteURI; - } else { - options = "static:(" + remoteURI; - } - if (inactivity) { - options += "?wireFormat.maxInactivityDuration=" + inactiveDuration + "&wireFormat.maxInactivityDurationInitalDelay=" + inactiveDuration + ")"; - } else { - options += ")"; - } - - if (failover) { - options += "?maxReconnectAttempts=0)"; - } - - options += "?useExponentialBackOff=" + exponentialBackOff; - DiscoveryNetworkConnector connector = new DiscoveryNetworkConnector(new URI(options)); - connector.setDynamicOnly(dynamicOnly); - connector.setNetworkTTL(networkTTL); - localBroker.addNetworkConnector(connector); - maxSetupTime = 2000; - if (useDuplexNetworkBridge) { - connector.setDuplex(true); - } - return connector; - } else { - throw new Exception("Remote broker has no registered connectors."); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberWithNetworkRestartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberWithNetworkRestartTest.java deleted file mode 100644 index 8528837d28..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriberWithNetworkRestartTest.java +++ /dev/null @@ -1,232 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.management.ObjectName; -import java.net.MalformedURLException; -import java.net.URI; -import java.util.Set; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.util.Wait; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import static org.junit.Assume.assumeNotNull; - -public class DurableSubscriberWithNetworkRestartTest extends JmsMultipleBrokersTestSupport { - - private static final Log LOG = LogFactory.getLog(DurableSubscriberWithNetworkRestartTest.class); - private static final String HUB = "HubBroker"; - private static final String SPOKE = "SpokeBroker"; - protected static final int MESSAGE_COUNT = 10; - public boolean dynamicOnly = false; - - public void testSendOnAReceiveOnBWithTransportDisconnectDynamicOnly() throws Exception { - dynamicOnly = true; - try { - testSendOnAReceiveOnBWithTransportDisconnect(); - } finally { - dynamicOnly = false; - } - } - - public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception { - bridge(SPOKE, HUB); - startAllBrokers(); - - verifyDuplexBridgeMbean(); - - // Setup connection - URI hubURI = brokers.get(HUB).broker.getTransportConnectors().get(0).getPublishableConnectURI(); - URI spokeURI = brokers.get(SPOKE).broker.getTransportConnectors().get(0).getPublishableConnectURI(); - ActiveMQConnectionFactory facHub = new ActiveMQConnectionFactory(hubURI); - ActiveMQConnectionFactory facSpoke = new ActiveMQConnectionFactory(spokeURI); - Connection conHub = facHub.createConnection(); - Connection conSpoke = facSpoke.createConnection(); - conHub.setClientID("clientHUB"); - conSpoke.setClientID("clientSPOKE"); - conHub.start(); - conSpoke.start(); - Session sesHub = conHub.createSession(false, Session.AUTO_ACKNOWLEDGE); - Session sesSpoke = conSpoke.createSession(false, Session.AUTO_ACKNOWLEDGE); - - ActiveMQTopic topic = new ActiveMQTopic("TEST.FOO"); - String consumerName = "consumerName"; - - // Setup consumers - MessageConsumer remoteConsumer = sesHub.createDurableSubscriber(topic, consumerName); - sleep(1000); - remoteConsumer.close(); - - // Setup producer - MessageProducer localProducer = sesSpoke.createProducer(topic); - localProducer.setDeliveryMode(DeliveryMode.PERSISTENT); - - final String payloadString = new String(new byte[10 * 1024]); - // Send messages - for (int i = 0; i < MESSAGE_COUNT; i++) { - Message test = sesSpoke.createTextMessage("test-" + i); - test.setStringProperty("payload", payloadString); - localProducer.send(test); - } - localProducer.close(); - - final String options = "?persistent=true&useJmx=true&deleteAllMessagesOnStartup=false"; - for (int i = 0; i < 2; i++) { - brokers.get(SPOKE).broker.stop(); - sleep(1000); - createBroker(new URI("broker:(tcp://localhost:61616)/" + SPOKE + options)); - bridge(SPOKE, HUB); - brokers.get(SPOKE).broker.start(); - LOG.info("restarted spoke..:" + i); - - assertTrue("got mbeans on restart", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return countMbeans(brokers.get(HUB).broker, "networkBridge", 20000) == (dynamicOnly ? 1 : 2); - } - })); - } - } - - private void verifyDuplexBridgeMbean() throws Exception { - assertEquals(1, countMbeans(brokers.get(HUB).broker, "networkBridge", 5000)); - } - - private int countMbeans(BrokerService broker, String type, int timeout) throws Exception { - final long expiryTime = System.currentTimeMillis() + timeout; - - if (!type.contains("=")) { - type = type + "=*"; - } - - final ObjectName beanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=" + broker.getBrokerName() + "," + type + ",*"); - Set mbeans = null; - int count = 0; - do { - if (timeout > 0) { - Thread.sleep(100); - } - - mbeans = broker.getManagementContext().queryNames(beanName, null); - if (mbeans != null) { - count = mbeans.size(); - LOG.info("Found: " + count + ", matching type: " + type); - for (ObjectName objectName : mbeans) { - LOG.info("" + objectName); - } - //} else { - //logAllMbeans(broker); - } - } while ((mbeans == null || mbeans.isEmpty()) && expiryTime > System.currentTimeMillis()); - - // If port 1099 is in use when the Broker starts, starting the jmx connector - // will fail. So, if we have no mbsc to query, skip the test. - if (timeout > 0) { - assumeNotNull(mbeans); - } - - return count; - - } - - private void logAllMbeans(BrokerService broker) throws MalformedURLException { - try { - // trace all existing MBeans - Set all = broker.getManagementContext().queryNames(null, null); - LOG.info("Total MBean count=" + all.size()); - for (ObjectName on : all) { - LOG.info(on); - } - } catch (Exception ignored) { - LOG.warn("getMBeanServer ex: " + ignored); - } - } - - public NetworkConnector bridge(String from, String to) throws Exception { - NetworkConnector networkConnector = bridgeBrokers(from, to, dynamicOnly, -1, true); - networkConnector.setSuppressDuplicateQueueSubscriptions(true); - networkConnector.setDecreaseNetworkConsumerPriority(true); - networkConnector.setConsumerTTL(1); - networkConnector.setDuplex(true); - return networkConnector; - } - - @Override - protected void startAllBrokers() throws Exception { - // Ensure HUB is started first so bridge will be active from the get go - BrokerItem brokerItem = brokers.get(HUB); - brokerItem.broker.start(); - brokerItem = brokers.get(SPOKE); - brokerItem.broker.start(); - sleep(600); - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(false); - super.setUp(); - createBrokers(true); - } - - private void createBrokers(boolean del) throws Exception { - final String options = "?persistent=true&useJmx=true&deleteAllMessagesOnStartup=" + del; - createBroker(new URI("broker:(tcp://localhost:61617)/" + HUB + options)); - createBroker(new URI("broker:(tcp://localhost:61616)/" + SPOKE + options)); - } - - @Override - protected void configureBroker(BrokerService broker) { - broker.setKeepDurableSubsActive(false); - broker.getManagementContext().setCreateConnector(false); - PolicyMap defaultPolcyMap = new PolicyMap(); - PolicyEntry defaultPolicy = new PolicyEntry(); - //defaultPolicy.setUseCache(false); - if (broker.getBrokerName().equals(HUB)) { - defaultPolicy.setStoreUsageHighWaterMark(2); - broker.getSystemUsage().getStoreUsage().setLimit(1 * 1024 * 1024); - } - defaultPolcyMap.setDefaultEntry(defaultPolicy); - broker.setDestinationPolicy(defaultPolcyMap); - broker.getSystemUsage().getMemoryUsage().setLimit(100 * 1024 * 1024); - } - - @Override - public void tearDown() throws Exception { - super.tearDown(); - } - - private void sleep(int milliSecondTime) { - try { - Thread.sleep(milliSecondTime); - } catch (InterruptedException igonred) { - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionActivationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionActivationTest.java deleted file mode 100644 index e3964b63b6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionActivationTest.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Session; -import java.io.File; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.Destination; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; - -public class DurableSubscriptionActivationTest extends org.apache.activemq.TestSupport { - - private BrokerService broker; - private Connection connection; - private ActiveMQTopic topic; - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://" + getName()); - } - - @Override - protected Connection createConnection() throws Exception { - Connection rc = super.createConnection(); - rc.setClientID(getName()); - return rc; - } - - @Override - protected void setUp() throws Exception { - topic = (ActiveMQTopic) createDestination(); - createBroker(true); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - destroyBroker(); - } - - protected void restartBroker() throws Exception { - destroyBroker(); - createBroker(false); - } - - private void createBroker(boolean delete) throws Exception { - broker = BrokerFactory.createBroker("broker:(vm://localhost)"); - broker.setKeepDurableSubsActive(true); - broker.setPersistent(true); - broker.setDeleteAllMessagesOnStartup(delete); - KahaDBPersistenceAdapter kahadb = new KahaDBPersistenceAdapter(); - kahadb.setDirectory(new File("activemq-data/" + getName() + "-kahadb")); - kahadb.setJournalMaxFileLength(500 * 1024); - broker.setPersistenceAdapter(kahadb); - broker.setBrokerName(getName()); - - // only if we pre-create the destinations - broker.setDestinations(new ActiveMQDestination[]{topic}); - - broker.start(); - broker.waitUntilStarted(); - - connection = createConnection(); - } - - private void destroyBroker() throws Exception { - if (connection != null) - connection.close(); - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } - - public void testActivateWithExistingTopic() throws Exception { - // create durable subscription - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId"); - - Destination d = broker.getDestination(topic); - assertTrue("More than one consumer found: " + d.getConsumers().size(), d.getConsumers().size() == 1); - - // restart the broker - restartBroker(); - - d = broker.getDestination(topic); - assertTrue("More than one consumer found: " + d.getConsumers().size(), d.getConsumers().size() == 1); - - // activate - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId"); - - assertTrue("More than one consumer found: " + d.getConsumers().size(), d.getConsumers().size() == 1); - - // re-activate - connection.close(); - connection = createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId"); - - assertTrue("More than one consumer found: " + d.getConsumers().size(), d.getConsumers().size() == 1); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionHangTestCase.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionHangTestCase.java deleted file mode 100644 index 06d4fa03fc..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionHangTestCase.java +++ /dev/null @@ -1,132 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.jms.Topic; -import javax.jms.TopicConnection; -import javax.jms.TopicSession; -import javax.jms.TopicSubscriber; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.commons.lang.RandomStringUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertNotNull; - -public class DurableSubscriptionHangTestCase { - - private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionHangTestCase.class); - final static String brokerName = "DurableSubscriptionHangTestCase"; - final static String clientID = "myId"; - private static final String topicName = "myTopic"; - private static final String durableSubName = "mySub"; - BrokerService brokerService; - - @Before - public void startBroker() throws Exception { - brokerService = new BrokerService(); - brokerService.setDeleteAllMessagesOnStartup(true); - brokerService.setBrokerName(brokerName); - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setExpireMessagesPeriod(5000); - policyMap.setDefaultEntry(defaultEntry); - brokerService.setDestinationPolicy(policyMap); - brokerService.start(); - } - - @After - public void brokerStop() throws Exception { - brokerService.stop(); - } - - @Test - public void testHanging() throws Exception { - registerDurableSubscription(); - produceExpiredAndOneNonExpiredMessages(); - TimeUnit.SECONDS.sleep(10); // make sure messages are expired - Message message = collectMessagesFromDurableSubscriptionForOneMinute(); - LOG.info("got message:" + message); - assertNotNull("Unable to read unexpired message", message); - } - - private void produceExpiredAndOneNonExpiredMessages() throws JMSException { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName); - TopicConnection connection = connectionFactory.createTopicConnection(); - TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic(topicName); - MessageProducer producer = session.createProducer(topic); - producer.setTimeToLive(TimeUnit.SECONDS.toMillis(1)); - for (int i = 0; i < 40000; i++) { - sendRandomMessage(session, producer); - } - producer.setTimeToLive(TimeUnit.DAYS.toMillis(1)); - sendRandomMessage(session, producer); - connection.close(); - LOG.info("produceExpiredAndOneNonExpiredMessages done"); - } - - private void registerDurableSubscription() throws JMSException { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName); - TopicConnection connection = connectionFactory.createTopicConnection(); - connection.setClientID(clientID); - TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = topicSession.createTopic(topicName); - TopicSubscriber durableSubscriber = topicSession.createDurableSubscriber(topic, durableSubName); - connection.start(); - durableSubscriber.close(); - connection.close(); - LOG.info("Durable Sub Registered"); - } - - private Message collectMessagesFromDurableSubscriptionForOneMinute() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName); - TopicConnection connection = connectionFactory.createTopicConnection(); - - connection.setClientID(clientID); - TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = topicSession.createTopic(topicName); - connection.start(); - TopicSubscriber subscriber = topicSession.createDurableSubscriber(topic, durableSubName); - LOG.info("About to receive messages"); - Message message = subscriber.receive(120000); - subscriber.close(); - connection.close(); - LOG.info("collectMessagesFromDurableSubscriptionForOneMinute done"); - - return message; - } - - private void sendRandomMessage(TopicSession session, MessageProducer producer) throws JMSException { - TextMessage textMessage = session.createTextMessage(); - textMessage.setText(RandomStringUtils.random(500, "abcdefghijklmnopqrstuvwxyz")); - producer.send(textMessage); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline1Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline1Test.java deleted file mode 100644 index 4b41b1282e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline1Test.java +++ /dev/null @@ -1,247 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.apache.activemq.TestSupport.PersistenceAdapterChoice; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; - -@RunWith(value = Parameterized.class) -public class DurableSubscriptionOffline1Test extends DurableSubscriptionOfflineTestBase { - - private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionOffline1Test.class); - - @Parameterized.Parameters(name = "{0}-{1}") - public static Collection getTestParameters() { - String osName = System.getProperty("os.name"); - LOG.debug("Running on [" + osName + "]"); - - List persistenceAdapterChoices = new ArrayList<>(); - - persistenceAdapterChoices.add(PersistenceAdapterChoice.KahaDB); - persistenceAdapterChoices.add(PersistenceAdapterChoice.JDBC); - if (!osName.equalsIgnoreCase("AIX") && !osName.equalsIgnoreCase("SunOS")) { - //choices.add(levelDb); - persistenceAdapterChoices.add(PersistenceAdapterChoice.LevelDB); - } - - List testParameters = new ArrayList<>(); - Boolean[] booleanValues = {Boolean.FALSE, Boolean.TRUE}; - List booleans = java.util.Arrays.asList(booleanValues); - for (Boolean booleanValue : booleans) { - for (PersistenceAdapterChoice persistenceAdapterChoice : persistenceAdapterChoices) { - Object[] currentChoice = {persistenceAdapterChoice, booleanValue}; - testParameters.add(currentChoice); - } - } - - return testParameters; - } - - public DurableSubscriptionOffline1Test(PersistenceAdapterChoice adapter, Boolean usePrioritySupport) { - this.defaultPersistenceAdapter = adapter; - this.usePrioritySupport = usePrioritySupport.booleanValue(); - LOG.debug(">>>> Created with adapter {} usePrioritySupport? {}", defaultPersistenceAdapter, usePrioritySupport); - - } - - @Test - public void testConsumeOnlyMatchedMessages() throws Exception { - // create durable subscription - Connection con = createConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); - - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); - - int sent = 0; - for (int i = 0; i < 10; i++) { - boolean filter = i % 2 == 1; - if (filter) - sent++; - - Message message = session.createMessage(); - message.setStringProperty("filter", filter ? "true" : "false"); - producer.send(topic, message); - } - - session.close(); - con.close(); - - // consume messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); - - Thread.sleep(3 * 1000); - - session.close(); - con.close(); - - assertEquals(sent, listener.count); - } - - @Test - public void testVerifyAllConsumedAreAcked() throws Exception { - // create durable subscription - Connection con = createConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); - - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); - - int sent = 0; - for (int i = 0; i < 10; i++) { - sent++; - Message message = session.createMessage(); - message.setStringProperty("filter", "true"); - producer.send(topic, message); - } - - Thread.sleep(1 * 1000); - - session.close(); - con.close(); - - // consume messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); - - Thread.sleep(3 * 1000); - - session.close(); - con.close(); - - LOG.info("Consumed: " + listener.count); - assertEquals(sent, listener.count); - - // consume messages again, should not get any - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); - - Thread.sleep(3 * 1000); - - session.close(); - con.close(); - - assertEquals(0, listener.count); - } - - @Test - public void testOfflineSubscriptionCanConsumeAfterOnlineSubs() throws Exception { - Connection con = createConnection("offCli1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); - - con = createConnection("offCli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); - - Connection con2 = createConnection("onlineCli1"); - Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer2 = session2.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener2 = new DurableSubscriptionOfflineTestListener(); - consumer2.setMessageListener(listener2); - - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); - - int sent = 0; - for (int i = 0; i < 10; i++) { - sent++; - Message message = session.createMessage(); - message.setStringProperty("filter", "true"); - producer.send(topic, message); - } - - Thread.sleep(1 * 1000); - session.close(); - con.close(); - - // test online subs - Thread.sleep(3 * 1000); - session2.close(); - con2.close(); - assertEquals(sent, listener2.count); - - // restart broker - broker.stop(); - createBroker(false /*deleteAllMessages*/); - - // test offline - con = createConnection("offCli1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - - Connection con3 = createConnection("offCli2"); - Session session3 = con3.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer3 = session3.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); - DurableSubscriptionOfflineTestListener listener3 = new DurableSubscriptionOfflineTestListener(); - consumer3.setMessageListener(listener3); - - Thread.sleep(3 * 1000); - - session.close(); - con.close(); - session3.close(); - con3.close(); - - assertEquals(sent, listener.count); - assertEquals(sent, listener3.count); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline2Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline2Test.java deleted file mode 100644 index c39d453fc8..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline2Test.java +++ /dev/null @@ -1,167 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.management.ObjectName; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.apache.activemq.broker.jmx.DurableSubscriptionViewMBean; -import org.apache.activemq.broker.jmx.TopicViewMBean; -import org.apache.activemq.util.Wait; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -@RunWith(value = Parameterized.class) -public class DurableSubscriptionOffline2Test extends DurableSubscriptionOfflineTestBase { - - private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionOffline2Test.class); - - @Parameterized.Parameters(name = "{0}") - public static Collection getTestParameters() { - Boolean[] f = {Boolean.FALSE}; - Boolean[] t = {Boolean.TRUE}; - List booleanChoices = new ArrayList<>(); - booleanChoices.add(f); - booleanChoices.add(t); - - return booleanChoices; - } - - public DurableSubscriptionOffline2Test(Boolean keepDurableSubsActive) { - this.keepDurableSubsActive = keepDurableSubsActive.booleanValue(); - - LOG.info(">>>> running {} with keepDurableSubsActive: {}", testName.getMethodName(), this.keepDurableSubsActive); - } - - @Test(timeout = 60 * 1000) - public void testJMXCountersWithOfflineSubs() throws Exception { - // create durable subscription 1 - Connection con = createConnection("cliId1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", null, true); - session.close(); - con.close(); - - // restart broker - broker.stop(); - createBroker(false /*deleteAllMessages*/); - - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); - - int sent = 0; - for (int i = 0; i < 10; i++) { - sent++; - Message message = session.createMessage(); - producer.send(topic, message); - } - session.close(); - con.close(); - - // consume some messages - con = createConnection("cliId1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, true); - - for (int i = 0; i < sent / 2; i++) { - Message m = consumer.receive(4000); - assertNotNull("got message: " + i, m); - LOG.info("Got :" + i + ", " + m); - } - - // check some counters while active - ObjectName activeDurableSubName = broker.getAdminView().getDurableTopicSubscribers()[0]; - LOG.info("active durable sub name: " + activeDurableSubName); - final DurableSubscriptionViewMBean durableSubscriptionView = (DurableSubscriptionViewMBean) broker.getManagementContext().newProxyInstance(activeDurableSubName, DurableSubscriptionViewMBean.class, true); - - assertTrue("is active", durableSubscriptionView.isActive()); - assertEquals("all enqueued", keepDurableSubsActive ? 10 : 0, durableSubscriptionView.getEnqueueCounter()); - assertTrue("correct waiting acks", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 5 == durableSubscriptionView.getMessageCountAwaitingAcknowledge(); - } - })); - assertEquals("correct dequeue", 5, durableSubscriptionView.getDequeueCounter()); - - ObjectName destinationName = broker.getAdminView().getTopics()[0]; - TopicViewMBean topicView = (TopicViewMBean) broker.getManagementContext().newProxyInstance(destinationName, TopicViewMBean.class, true); - assertEquals("correct enqueue", 10, topicView.getEnqueueCount()); - assertEquals("still zero dequeue, we don't decrement on each sub ack to stop exceeding the enqueue count with multiple subs", 0, topicView.getDequeueCount()); - assertEquals("inflight", 5, topicView.getInFlightCount()); - - session.close(); - con.close(); - - // check some counters when inactive - ObjectName inActiveDurableSubName = broker.getAdminView().getInactiveDurableTopicSubscribers()[0]; - LOG.info("inactive durable sub name: " + inActiveDurableSubName); - DurableSubscriptionViewMBean durableSubscriptionView1 = (DurableSubscriptionViewMBean) broker.getManagementContext().newProxyInstance(inActiveDurableSubName, DurableSubscriptionViewMBean.class, true); - - assertTrue("is not active", !durableSubscriptionView1.isActive()); - assertEquals("all enqueued", keepDurableSubsActive ? 10 : 0, durableSubscriptionView1.getEnqueueCounter()); - assertEquals("correct awaiting ack", 0, durableSubscriptionView1.getMessageCountAwaitingAcknowledge()); - assertEquals("correct dequeue", keepDurableSubsActive ? 5 : 0, durableSubscriptionView1.getDequeueCounter()); - - // destination view - assertEquals("correct enqueue", 10, topicView.getEnqueueCount()); - assertEquals("still zero dequeue, we don't decrement on each sub ack to stop exceeding the enqueue count with multiple subs", 0, topicView.getDequeueCount()); - assertEquals("inflight back to 0 after deactivate", 0, topicView.getInFlightCount()); - - // consume the rest - con = createConnection("cliId1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session.createDurableSubscriber(topic, "SubsId", null, true); - - for (int i = 0; i < sent / 2; i++) { - Message m = consumer.receive(30000); - assertNotNull("got message: " + i, m); - LOG.info("Got :" + i + ", " + m); - } - - activeDurableSubName = broker.getAdminView().getDurableTopicSubscribers()[0]; - LOG.info("durable sub name: " + activeDurableSubName); - final DurableSubscriptionViewMBean durableSubscriptionView2 = (DurableSubscriptionViewMBean) broker.getManagementContext().newProxyInstance(activeDurableSubName, DurableSubscriptionViewMBean.class, true); - - assertTrue("is active", durableSubscriptionView2.isActive()); - assertEquals("all enqueued", keepDurableSubsActive ? 10 : 0, durableSubscriptionView2.getEnqueueCounter()); - assertTrue("correct dequeue", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - long val = durableSubscriptionView2.getDequeueCounter(); - LOG.info("dequeue count:" + val); - return 10 == val; - } - })); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline3Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline3Test.java deleted file mode 100644 index 9d621f5bf9..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline3Test.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.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.apache.activemq.TestSupport.PersistenceAdapterChoice; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -@RunWith(value = Parameterized.class) -public class DurableSubscriptionOffline3Test extends DurableSubscriptionOfflineTestBase { - - private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionOffline3Test.class); - - @Parameterized.Parameters(name = "{0}") - public static Collection getTestParameters() { - String osName = System.getProperty("os.name"); - LOG.debug("Running on [" + osName + "]"); - - PersistenceAdapterChoice[] kahaDb = {PersistenceAdapterChoice.KahaDB}; - PersistenceAdapterChoice[] jdbc = {PersistenceAdapterChoice.JDBC}; - List choices = new ArrayList<>(); - choices.add(kahaDb); - choices.add(jdbc); - if (!osName.equalsIgnoreCase("AIX") && !osName.equalsIgnoreCase("SunOS")) { - PersistenceAdapterChoice[] levelDb = {PersistenceAdapterChoice.LevelDB}; - choices.add(levelDb); - } - - return choices; - } - - public DurableSubscriptionOffline3Test(PersistenceAdapterChoice persistenceAdapterChoice) { - this.defaultPersistenceAdapter = persistenceAdapterChoice; - - LOG.info(">>>> running {} with persistenceAdapterChoice: {}", testName.getMethodName(), this.defaultPersistenceAdapter); - } - - @Test(timeout = 60 * 1000) - public void testInterleavedOfflineSubscriptionCanConsume() throws Exception { - // create durable subscription 1 - Connection con = createConnection("cliId1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); - - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); - - int sent = 0; - for (int i = 0; i < 10; i++) { - sent++; - Message message = session.createMessage(); - message.setStringProperty("filter", "true"); - producer.send(topic, message); - } - - Thread.sleep(1 * 1000); - - // create durable subscription 2 - Connection con2 = createConnection("cliId2"); - Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer2 = session2.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener2 = new DurableSubscriptionOfflineTestListener(); - consumer2.setMessageListener(listener2); - - assertEquals(0, listener2.count); - session2.close(); - con2.close(); - - // send some more - for (int i = 0; i < 10; i++) { - sent++; - Message message = session.createMessage(); - message.setStringProperty("filter", "true"); - producer.send(topic, message); - } - - Thread.sleep(1 * 1000); - session.close(); - con.close(); - - con2 = createConnection("cliId2"); - session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer2 = session2.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - listener2 = new DurableSubscriptionOfflineTestListener("cliId2"); - consumer2.setMessageListener(listener2); - // test online subs - Thread.sleep(3 * 1000); - - assertEquals(10, listener2.count); - - // consume all messages - con = createConnection("cliId1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener("cliId1"); - consumer.setMessageListener(listener); - - Thread.sleep(3 * 1000); - - session.close(); - con.close(); - - assertEquals("offline consumer got all", sent, listener.count); - } - - private static String filter = "$a='A1' AND (($b=true AND $c=true) OR ($d='D1' OR $d='D2'))"; - - @Test(timeout = 60 * 1000) - public void testMixOfOnLineAndOfflineSubsGetAllMatched() throws Exception { - // create offline subs 1 - Connection con = createConnection("offCli1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", filter, true); - session.close(); - con.close(); - - // create offline subs 2 - con = createConnection("offCli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", filter, true); - session.close(); - con.close(); - - // create online subs - Connection con2 = createConnection("onlineCli1"); - Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer2 = session2.createDurableSubscriber(topic, "SubsId", filter, true); - DurableSubscriptionOfflineTestListener listener2 = new DurableSubscriptionOfflineTestListener(); - consumer2.setMessageListener(listener2); - - // create non-durable consumer - Connection con4 = createConnection("nondurableCli"); - Session session4 = con4.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer4 = session4.createConsumer(topic, filter, true); - DurableSubscriptionOfflineTestListener listener4 = new DurableSubscriptionOfflineTestListener(); - consumer4.setMessageListener(listener4); - - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); - - boolean hasRelevant = false; - int filtered = 0; - for (int i = 0; i < 100; i++) { - int postf = (int) (Math.random() * 9) + 1; - String d = "D" + postf; - - if ("D1".equals(d) || "D2".equals(d)) { - hasRelevant = true; - filtered++; - } - - Message message = session.createMessage(); - message.setStringProperty("$a", "A1"); - message.setStringProperty("$d", d); - producer.send(topic, message); - } - - Message message = session.createMessage(); - message.setStringProperty("$a", "A1"); - message.setBooleanProperty("$b", true); - message.setBooleanProperty("$c", hasRelevant); - producer.send(topic, message); - - if (hasRelevant) - filtered++; - - Thread.sleep(1 * 1000); - session.close(); - con.close(); - - Thread.sleep(3 * 1000); - - // test non-durable consumer - session4.close(); - con4.close(); - assertEquals(filtered, listener4.count); // succeeded! - - // test online subs - session2.close(); - con2.close(); - assertEquals(filtered, listener2.count); // succeeded! - - // test offline 1 - con = createConnection("offCli1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", filter, true); - DurableSubscriptionOfflineTestListener listener = new FilterCheckListener(); - consumer.setMessageListener(listener); - - Thread.sleep(3 * 1000); - session.close(); - con.close(); - - assertEquals(filtered, listener.count); - - // test offline 2 - Connection con3 = createConnection("offCli2"); - Session session3 = con3.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer3 = session3.createDurableSubscriber(topic, "SubsId", filter, true); - DurableSubscriptionOfflineTestListener listener3 = new FilterCheckListener(); - consumer3.setMessageListener(listener3); - - Thread.sleep(3 * 1000); - session3.close(); - con3.close(); - - assertEquals(filtered, listener3.count); - assertTrue("no unexpected exceptions: " + exceptions, exceptions.isEmpty()); - } - - @Test(timeout = 60 * 1000) - public void testOfflineSubscriptionWithSelectorAfterRestart() throws Exception { - - if (PersistenceAdapterChoice.LevelDB == defaultPersistenceAdapter) { - // https://issues.apache.org/jira/browse/AMQ-4296 - return; - } - - // create offline subs 1 - Connection con = createConnection("offCli1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); - - // create offline subs 2 - con = createConnection("offCli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); - - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); - - int filtered = 0; - for (int i = 0; i < 10; i++) { - boolean filter = (int) (Math.random() * 2) >= 1; - if (filter) - filtered++; - - Message message = session.createMessage(); - message.setStringProperty("filter", filter ? "true" : "false"); - producer.send(topic, message); - } - - LOG.info("sent: " + filtered); - Thread.sleep(1 * 1000); - session.close(); - con.close(); - - // restart broker - Thread.sleep(3 * 1000); - broker.stop(); - createBroker(false /*deleteAllMessages*/); - - // send more messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(null); - - for (int i = 0; i < 10; i++) { - boolean filter = (int) (Math.random() * 2) >= 1; - if (filter) - filtered++; - - Message message = session.createMessage(); - message.setStringProperty("filter", filter ? "true" : "false"); - producer.send(topic, message); - } - - LOG.info("after restart, total sent with filter='true': " + filtered); - Thread.sleep(1 * 1000); - session.close(); - con.close(); - - // test offline subs - con = createConnection("offCli1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener("1>"); - consumer.setMessageListener(listener); - - Connection con3 = createConnection("offCli2"); - Session session3 = con3.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer3 = session3.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener3 = new DurableSubscriptionOfflineTestListener(); - consumer3.setMessageListener(listener3); - - Thread.sleep(3 * 1000); - - session.close(); - con.close(); - session3.close(); - con3.close(); - - assertEquals(filtered, listener.count); - assertEquals(filtered, listener3.count); - } - - @Test(timeout = 60 * 1000) - public void testOfflineSubscriptionAfterRestart() throws Exception { - // create offline subs 1 - Connection con = createConnection("offCli1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, false); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); - - // send messages - MessageProducer producer = session.createProducer(null); - - int sent = 0; - for (int i = 0; i < 10; i++) { - sent++; - Message message = session.createMessage(); - message.setStringProperty("filter", "false"); - producer.send(topic, message); - } - - LOG.info("sent: " + sent); - Thread.sleep(5 * 1000); - session.close(); - con.close(); - - assertEquals(sent, listener.count); - - // restart broker - Thread.sleep(3 * 1000); - broker.stop(); - createBroker(false /*deleteAllMessages*/); - - // send more messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(null); - - for (int i = 0; i < 10; i++) { - sent++; - Message message = session.createMessage(); - message.setStringProperty("filter", "false"); - producer.send(topic, message); - } - - LOG.info("after restart, sent: " + sent); - Thread.sleep(1 * 1000); - session.close(); - con.close(); - - // test offline subs - con = createConnection("offCli1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session.createDurableSubscriber(topic, "SubsId", null, true); - consumer.setMessageListener(listener); - - Thread.sleep(3 * 1000); - - session.close(); - con.close(); - - assertEquals(sent, listener.count); - } - - public class FilterCheckListener extends DurableSubscriptionOfflineTestListener { - - @Override - public void onMessage(Message message) { - count++; - - try { - Object b = message.getObjectProperty("$b"); - if (b != null) { - boolean c = message.getBooleanProperty("$c"); - assertTrue("", c); - } else { - String d = message.getStringProperty("$d"); - assertTrue("", "D1".equals(d) || "D2".equals(d)); - } - } catch (JMSException e) { - e.printStackTrace(); - exceptions.add(e); - } - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline4Test.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline4Test.java deleted file mode 100644 index e085926dfa..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOffline4Test.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.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.util.Wait; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertTrue; - -@RunWith(value = Parameterized.class) -public class DurableSubscriptionOffline4Test extends DurableSubscriptionOfflineTestBase { - - private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionOffline4Test.class); - - @Parameterized.Parameters(name = "keepDurableSubsActive_{0}") - public static Collection getTestParameters() { - Boolean[] f = {Boolean.FALSE}; - Boolean[] t = {Boolean.TRUE}; - List booleanChoices = new ArrayList<>(); - booleanChoices.add(f); - booleanChoices.add(t); - - return booleanChoices; - } - - public DurableSubscriptionOffline4Test(Boolean keepDurableSubsActive) { - this.journalMaxFileLength = 64 * 1024; - this.keepDurableSubsActive = keepDurableSubsActive.booleanValue(); - - LOG.info(">>>> running {} with keepDurableSubsActive: {}, journalMaxFileLength", testName.getMethodName(), this.keepDurableSubsActive, journalMaxFileLength); - } - - @Test(timeout = 60 * 1000) - // https://issues.apache.org/jira/browse/AMQ-3206 - public void testCleanupDeletedSubAfterRestart() throws Exception { - Connection con = createConnection("cli1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", null, true); - session.close(); - con.close(); - - con = createConnection("cli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", null, true); - session.close(); - con.close(); - - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); - - final int toSend = 500; - final String payload = Arrays.toString(new byte[40 * 1024]); - int sent = 0; - for (int i = sent; i < toSend; i++) { - Message message = session.createTextMessage(payload); - message.setStringProperty("filter", "false"); - message.setIntProperty("ID", i); - producer.send(topic, message); - sent++; - } - con.close(); - LOG.info("sent: " + sent); - - // kill off cli1 - con = createConnection("cli1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.unsubscribe("SubsId"); - - destroyBroker(); - createBroker(false); - - con = createConnection("cli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, true); - final DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); - assertTrue("got all sent", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Want: " + toSend + ", current: " + listener.count); - return listener.count == toSend; - } - })); - session.close(); - con.close(); - - destroyBroker(); - createBroker(false); - final KahaDBPersistenceAdapter pa = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - assertTrue("Should have less than three journal files left but was: " + pa.getStore().getJournal().getFileMap().size(), Wait.waitFor(new Wait.Condition() { - - @Override - public boolean isSatisified() throws Exception { - return pa.getStore().getJournal().getFileMap().size() <= 3; - } - })); - } -} - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOfflineTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOfflineTest.java deleted file mode 100644 index 6aad7f0114..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionOfflineTest.java +++ /dev/null @@ -1,870 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.util.HashSet; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.command.MessageId; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.store.kahadb.disk.page.PageFile; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -public class DurableSubscriptionOfflineTest extends DurableSubscriptionOfflineTestBase { - - private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionOfflineTest.class); - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + getName(true)); - connectionFactory.setWatchTopicAdvisories(false); - return connectionFactory; - } - - @Test(timeout = 60 * 1000) - public void testConsumeAllMatchedMessages() throws Exception { - // create durable subscription - Connection con = createConnection(); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); - - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); - - int sent = 0; - for (int i = 0; i < 10; i++) { - sent++; - Message message = session.createMessage(); - message.setStringProperty("filter", "true"); - producer.send(topic, message); - } - - Thread.sleep(1 * 1000); - - session.close(); - con.close(); - - // consume messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); - - Thread.sleep(3 * 1000); - - session.close(); - con.close(); - - assertEquals(sent, listener.count); - } - - @Test(timeout = 60 * 1000) - public void testTwoOfflineSubscriptionCanConsume() throws Exception { - // create durable subscription 1 - Connection con = createConnection("cliId1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); - - // create durable subscription 2 - Connection con2 = createConnection("cliId2"); - Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer2 = session2.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener2 = new DurableSubscriptionOfflineTestListener(); - consumer2.setMessageListener(listener2); - - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); - - int sent = 0; - for (int i = 0; i < 10; i++) { - sent++; - Message message = session.createMessage(); - message.setStringProperty("filter", "true"); - producer.send(topic, message); - } - - Thread.sleep(1 * 1000); - session.close(); - con.close(); - - // test online subs - Thread.sleep(3 * 1000); - session2.close(); - con2.close(); - - assertEquals(sent, listener2.count); - - // consume messages - con = createConnection("cliId1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); - - Thread.sleep(3 * 1000); - - session.close(); - con.close(); - - assertEquals("offline consumer got all", sent, listener.count); - } - - @Test(timeout = 60 * 1000) - public void testRemovedDurableSubDeletes() throws Exception { - String filter = "$a='A1' AND (($b=true AND $c=true) OR ($d='D1' OR $d='D2'))"; - // create durable subscription 1 - Connection con = createConnection("cliId1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); - - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); - - for (int i = 0; i < 10; i++) { - Message message = session.createMessage(); - message.setStringProperty("filter", "true"); - producer.send(topic, message); - } - - Thread.sleep(1 * 1000); - - Connection con2 = createConnection("cliId1"); - Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); - session2.unsubscribe("SubsId"); - session2.close(); - con2.close(); - - // see if retroactive can consumer any - topic = new ActiveMQTopic(topic.getPhysicalName() + "?consumer.retroactive=true"); - con = createConnection("offCli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", filter, true); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); - session.close(); - con.close(); - assertEquals(0, listener.count); - } - - @Test(timeout = 60 * 1000) - public void testRemovedDurableSubDeletesFromIndex() throws Exception { - - if (!(broker.getPersistenceAdapter() instanceof KahaDBPersistenceAdapter)) { - return; - } - - final int numMessages = 2750; - - KahaDBPersistenceAdapter kahaDBPersistenceAdapter = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter(); - PageFile pageFile = kahaDBPersistenceAdapter.getStore().getPageFile(); - LOG.info("PageCount " + pageFile.getPageCount() + " f:" + pageFile.getFreePageCount() + ", fileSize:" + pageFile.getFile().length()); - - long lastDiff = 0; - for (int repeats = 0; repeats < 2; repeats++) { - - LOG.info("Iteration: " + repeats + " Count:" + pageFile.getPageCount() + " f:" + pageFile.getFreePageCount()); - - Connection con = createConnection("cliId1" + "-" + repeats); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); - - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); - - for (int i = 0; i < numMessages; i++) { - Message message = session.createMessage(); - message.setStringProperty("filter", "true"); - producer.send(topic, message); - } - con.close(); - - Connection con2 = createConnection("cliId1" + "-" + repeats); - Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); - session2.unsubscribe("SubsId"); - session2.close(); - con2.close(); - - LOG.info("PageCount " + pageFile.getPageCount() + " f:" + pageFile.getFreePageCount() + " diff: " + (pageFile.getPageCount() - pageFile.getFreePageCount()) + " fileSize:" + pageFile.getFile().length()); - - if (lastDiff != 0) { - assertEquals("Only use X pages per iteration: " + repeats, lastDiff, pageFile.getPageCount() - pageFile.getFreePageCount()); - } - lastDiff = pageFile.getPageCount() - pageFile.getFreePageCount(); - } - } - - @Test(timeout = 60 * 1000) - public void testInterleavedOfflineSubscriptionCanConsumeAfterUnsub() throws Exception { - // create offline subs 1 - Connection con = createConnection("offCli1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); - - // create offline subs 2 - con = createConnection("offCli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", null, true); - session.close(); - con.close(); - - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); - - int sent = 0; - for (int i = 0; i < 10; i++) { - boolean filter = (int) (Math.random() * 2) >= 1; - - sent++; - - Message message = session.createMessage(); - message.setStringProperty("filter", filter ? "true" : "false"); - producer.send(topic, message); - } - - Thread.sleep(1 * 1000); - - Connection con2 = createConnection("offCli1"); - Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE); - session2.unsubscribe("SubsId"); - session2.close(); - con2.close(); - - // consume all messages - con = createConnection("offCli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, true); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener("SubsId"); - consumer.setMessageListener(listener); - - Thread.sleep(3 * 1000); - - session.close(); - con.close(); - - assertEquals("offline consumer got all", sent, listener.count); - } - - @Test(timeout = 60 * 1000) - public void testNoDuplicateOnConcurrentSendTranCommitAndActivate() throws Exception { - final int messageCount = 1000; - Connection con = null; - Session session = null; - final int numConsumers = 10; - for (int i = 0; i <= numConsumers; i++) { - con = createConnection("cli" + i); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", null, true); - session.close(); - con.close(); - } - - class CheckForDupsClient implements Runnable { - - HashSet ids = new HashSet<>(); - final int id; - - public CheckForDupsClient(int id) { - this.id = id; - } - - @Override - public void run() { - try { - Connection con = createConnection("cli" + id); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - for (int j = 0; j < 2; j++) { - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, true); - for (int i = 0; i < messageCount / 2; i++) { - Message message = consumer.receive(4000); - assertNotNull(message); - long producerSequenceId = new MessageId(message.getJMSMessageID()).getProducerSequenceId(); - assertTrue("ID=" + id + " not a duplicate: " + producerSequenceId, ids.add(producerSequenceId)); - } - consumer.close(); - } - - // verify no duplicates left - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, true); - Message message = consumer.receive(4000); - if (message != null) { - long producerSequenceId = new MessageId(message.getJMSMessageID()).getProducerSequenceId(); - assertTrue("ID=" + id + " not a duplicate: " + producerSequenceId, ids.add(producerSequenceId)); - } - assertNull(message); - - session.close(); - con.close(); - } catch (Throwable e) { - e.printStackTrace(); - exceptions.add(e); - } - } - } - - final String payLoad = new String(new byte[1000]); - con = createConnection(); - final Session sendSession = con.createSession(true, Session.SESSION_TRANSACTED); - MessageProducer producer = sendSession.createProducer(topic); - for (int i = 0; i < messageCount; i++) { - producer.send(sendSession.createTextMessage(payLoad)); - } - - ExecutorService executorService = Executors.newCachedThreadPool(); - - // concurrent commit and activate - executorService.execute(new Runnable() { - @Override - public void run() { - try { - sendSession.commit(); - } catch (JMSException e) { - e.printStackTrace(); - exceptions.add(e); - } - } - }); - for (int i = 0; i < numConsumers; i++) { - executorService.execute(new CheckForDupsClient(i)); - } - - executorService.shutdown(); - executorService.awaitTermination(5, TimeUnit.MINUTES); - con.close(); - - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - } - - @Test(timeout = 2 * 60 * 1000) - public void testOrderOnActivateDeactivate() throws Exception { - for (int i = 0; i < 10; i++) { - LOG.info("Iteration: " + i); - doTestOrderOnActivateDeactivate(); - broker.stop(); - broker.waitUntilStopped(); - createBroker(true /*deleteAllMessages*/); - } - } - - public void doTestOrderOnActivateDeactivate() throws Exception { - final int messageCount = 1000; - Connection con = null; - Session session = null; - final int numConsumers = 4; - for (int i = 0; i <= numConsumers; i++) { - con = createConnection("cli" + i); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", null, true); - session.close(); - con.close(); - } - - final String url = "failover:(tcp://localhost:" + (broker.getTransportConnectors().get(1).getConnectUri()).getPort() + "?wireFormat.maxInactivityDuration=0)?" + "jms.watchTopicAdvisories=false&" + "jms.alwaysSyncSend=true&jms.dispatchAsync=true&" + "jms.sendAcksAsync=true&" + "initialReconnectDelay=100&maxReconnectDelay=30000&" + "useExponentialBackOff=true"; - final ActiveMQConnectionFactory clientFactory = new ActiveMQConnectionFactory(url); - - class CheckOrderClient implements Runnable { - - final int id; - int runCount = 0; - - public CheckOrderClient(int id) { - this.id = id; - } - - @Override - public void run() { - try { - synchronized (this) { - Connection con = clientFactory.createConnection(); - con.setClientID("cli" + id); - con.start(); - Session session = con.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, true); - int nextId = 0; - - ++runCount; - int i = 0; - for (; i < messageCount / 2; i++) { - Message message = consumer.receiveNoWait(); - if (message == null) { - break; - } - long producerSequenceId = new MessageId(message.getJMSMessageID()).getProducerSequenceId(); - assertEquals(id + " expected order: runCount: " + runCount + " id: " + message.getJMSMessageID(), ++nextId, producerSequenceId); - } - LOG.info(con.getClientID() + " peeked " + i); - session.close(); - con.close(); - } - } catch (Throwable e) { - e.printStackTrace(); - exceptions.add(e); - } - } - } - - Runnable producer = new Runnable() { - final String payLoad = new String(new byte[600]); - - @Override - public void run() { - try { - Connection con = createConnection(); - final Session sendSession = con.createSession(true, Session.SESSION_TRANSACTED); - MessageProducer producer = sendSession.createProducer(topic); - for (int i = 0; i < messageCount; i++) { - producer.send(sendSession.createTextMessage(payLoad)); - } - LOG.info("About to commit: " + messageCount); - sendSession.commit(); - LOG.info("committed: " + messageCount); - con.close(); - } catch (Exception e) { - e.printStackTrace(); - exceptions.add(e); - } - } - }; - - ExecutorService executorService = Executors.newCachedThreadPool(); - - // concurrent commit and activate - for (int i = 0; i < numConsumers; i++) { - final CheckOrderClient client = new CheckOrderClient(i); - for (int j = 0; j < 100; j++) { - executorService.execute(client); - } - } - executorService.execute(producer); - - executorService.shutdown(); - executorService.awaitTermination(5, TimeUnit.MINUTES); - con.close(); - - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - } - - @Test(timeout = 60 * 1000) - public void testUnmatchedSubUnsubscribeDeletesAll() throws Exception { - // create offline subs 1 - Connection con = createConnection("offCli1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - session.close(); - con.close(); - - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); - - int filtered = 0; - for (int i = 0; i < 10; i++) { - boolean filter = (i % 2 == 0); //(int) (Math.random() * 2) >= 1; - if (filter) - filtered++; - - Message message = session.createMessage(); - message.setStringProperty("filter", filter ? "true" : "false"); - producer.send(topic, message); - } - - LOG.info("sent: " + filtered); - Thread.sleep(1 * 1000); - session.close(); - con.close(); - - // test offline subs - con = createConnection("offCli1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.unsubscribe("SubsId"); - session.close(); - con.close(); - - con = createConnection("offCli1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); - - Thread.sleep(3 * 1000); - - session.close(); - con.close(); - - assertEquals(0, listener.count); - } - - @Test(timeout = 60 * 1000) - public void testAllConsumed() throws Exception { - final String filter = "filter = 'true'"; - Connection con = createConnection("cli1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", filter, true); - session.close(); - con.close(); - - con = createConnection("cli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", filter, true); - session.close(); - con.close(); - - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); - - int sent = 0; - for (int i = 0; i < 10; i++) { - Message message = session.createMessage(); - message.setStringProperty("filter", "true"); - producer.send(topic, message); - sent++; - } - - LOG.info("sent: " + sent); - Thread.sleep(1 * 1000); - session.close(); - con.close(); - - con = createConnection("cli1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", filter, true); - DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); - Thread.sleep(3 * 1000); - session.close(); - con.close(); - - assertEquals(sent, listener.count); - - LOG.info("cli2 pull 2"); - con = createConnection("cli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session.createDurableSubscriber(topic, "SubsId", filter, true); - assertNotNull("got message", consumer.receive(2000)); - assertNotNull("got message", consumer.receive(2000)); - session.close(); - con.close(); - - // send messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(null); - - sent = 0; - for (int i = 0; i < 2; i++) { - Message message = session.createMessage(); - message.setStringProperty("filter", i == 1 ? "true" : "false"); - producer.send(topic, message); - sent++; - } - LOG.info("sent: " + sent); - Thread.sleep(1 * 1000); - session.close(); - con.close(); - - LOG.info("cli1 again, should get 1 new ones"); - con = createConnection("cli1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session.createDurableSubscriber(topic, "SubsId", filter, true); - listener = new DurableSubscriptionOfflineTestListener(); - consumer.setMessageListener(listener); - Thread.sleep(3 * 1000); - session.close(); - con.close(); - - assertEquals(1, listener.count); - } - - // https://issues.apache.org/jira/browse/AMQ-3190 - @Test(timeout = 60 * 1000) - public void testNoMissOnMatchingSubAfterRestart() throws Exception { - - final String filter = "filter = 'true'"; - Connection con = createConnection("cli1"); - Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", filter, true); - session.close(); - con.close(); - - // send unmatched messages - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(null); - - int sent = 0; - // message for cli1 to keep it interested - Message message = session.createMessage(); - message.setStringProperty("filter", "true"); - message.setIntProperty("ID", 0); - producer.send(topic, message); - sent++; - - for (int i = sent; i < 10; i++) { - message = session.createMessage(); - message.setStringProperty("filter", "false"); - message.setIntProperty("ID", i); - producer.send(topic, message); - sent++; - } - con.close(); - LOG.info("sent: " + sent); - - // new sub at id 10 - con = createConnection("cli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId", filter, true); - session.close(); - con.close(); - - destroyBroker(); - createBroker(false); - - con = createConnection(); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(null); - - for (int i = sent; i < 30; i++) { - message = session.createMessage(); - message.setStringProperty("filter", "true"); - message.setIntProperty("ID", i); - producer.send(topic, message); - sent++; - } - con.close(); - LOG.info("sent: " + sent); - - // pick up the first of the next twenty messages - con = createConnection("cli2"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", filter, true); - Message m = consumer.receive(3000); - assertEquals("is message 10", 10, m.getIntProperty("ID")); - - session.close(); - con.close(); - - // pick up the first few messages for client1 - con = createConnection("cli1"); - session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session.createDurableSubscriber(topic, "SubsId", filter, true); - m = consumer.receive(3000); - assertEquals("is message 0", 0, m.getIntProperty("ID")); - m = consumer.receive(3000); - assertEquals("is message 10", 10, m.getIntProperty("ID")); - - session.close(); - con.close(); - } - - // // https://issues.apache.org/jira/browse/AMQ-3768 - // public void testPageReuse() throws Exception { - // Connection con = null; - // Session session = null; - // - // final int numConsumers = 115; - // for (int i=0; i<=numConsumers;i++) { - // con = createConnection("cli" + i); - // session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - // session.createDurableSubscriber(topic, "SubsId", null, true); - // session.close(); - // con.close(); - // } - // - // // populate ack locations - // con = createConnection(); - // session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - // MessageProducer producer = session.createProducer(null); - // Message message = session.createTextMessage(new byte[10].toString()); - // producer.send(topic, message); - // con.close(); - // - // // we have a split, remove all but the last so that - // // the head pageid changes in the acklocations listindex - // for (int i=0; i<=numConsumers -1; i++) { - // con = createConnection("cli" + i); - // session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - // session.unsubscribe("SubsId"); - // session.close(); - // con.close(); - // } - // - // destroyBroker(); - // createBroker(false); - // - // // create a bunch more subs to reuse the freed page and get us in a knot - // for (int i=1; i<=numConsumers;i++) { - // con = createConnection("cli" + i); - // session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - // session.createDurableSubscriber(topic, "SubsId", filter, true); - // session.close(); - // con.close(); - // } - // } - // - // public void testRedeliveryFlag() throws Exception { - // - // Connection con; - // Session session; - // final int numClients = 2; - // for (int i=0; i exceptions = new ArrayList<>(); - protected ActiveMQConnectionFactory connectionFactory; - protected boolean isTopic = true; - public PersistenceAdapterChoice defaultPersistenceAdapter = PersistenceAdapterChoice.KahaDB; - - @Rule - public TestName testName = new TestName(); - - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + getName(true)); - connectionFactory.setWatchTopicAdvisories(false); - return connectionFactory; - } - - protected Connection createConnection() throws Exception { - return createConnection("cliName"); - } - - protected Connection createConnection(String name) throws Exception { - ConnectionFactory connectionFactory1 = createConnectionFactory(); - Connection connection = connectionFactory1.createConnection(); - connection.setClientID(name); - connection.start(); - return connection; - } - - public ActiveMQConnectionFactory getConnectionFactory() throws Exception { - if (connectionFactory == null) { - connectionFactory = createConnectionFactory(); - assertTrue("Should have created a connection factory!", connectionFactory != null); - } - return connectionFactory; - } - - @Before - public void setUp() throws Exception { - exceptions.clear(); - topic = (ActiveMQTopic) createDestination(); - createBroker(); - } - - @After - public void tearDown() throws Exception { - destroyBroker(); - } - - protected void createBroker() throws Exception { - createBroker(true); - } - - protected void createBroker(boolean deleteAllMessages) throws Exception { - String currentTestName = getName(true); - broker = BrokerFactory.createBroker("broker:(vm://" + currentTestName + ")"); - broker.setBrokerName(currentTestName); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - broker.getManagementContext().setCreateConnector(false); - broker.setAdvisorySupport(false); - broker.setKeepDurableSubsActive(keepDurableSubsActive); - broker.addConnector("tcp://0.0.0.0:0"); - - if (usePrioritySupport) { - PolicyEntry policy = new PolicyEntry(); - policy.setPrioritizedMessages(true); - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(policy); - broker.setDestinationPolicy(policyMap); - } - - setDefaultPersistenceAdapter(broker); - if (broker.getPersistenceAdapter() instanceof JDBCPersistenceAdapter) { - // ensure it kicks in during tests - ((JDBCPersistenceAdapter) broker.getPersistenceAdapter()).setCleanupPeriod(2 * 1000); - } else if (broker.getPersistenceAdapter() instanceof KahaDBPersistenceAdapter) { - // have lots of journal files - ((KahaDBPersistenceAdapter) broker.getPersistenceAdapter()).setJournalMaxFileLength(journalMaxFileLength); - } - broker.start(); - broker.waitUntilStarted(); - } - - protected void destroyBroker() throws Exception { - if (broker != null) - broker.stop(); - } - - protected Destination createDestination(String subject) { - if (isTopic) { - return new ActiveMQTopic(subject); - } else { - return new ActiveMQQueue(subject); - } - } - - protected Destination createDestination() { - return createDestination(getDestinationString()); - } - - /** - * Returns the name of the destination used in this test case - */ - protected String getDestinationString() { - return getClass().getName() + "." + getName(true); - } - - public String getName() { - return getName(false); - } - - protected String getName(boolean original) { - String currentTestName = testName.getMethodName(); - currentTestName = currentTestName.replace("[", ""); - currentTestName = currentTestName.replace("]", ""); - return currentTestName; - } - - public PersistenceAdapter setDefaultPersistenceAdapter(BrokerService broker) throws IOException { - return setPersistenceAdapter(broker, defaultPersistenceAdapter); - } - - public PersistenceAdapter setPersistenceAdapter(BrokerService broker, - PersistenceAdapterChoice choice) throws IOException { - PersistenceAdapter adapter = null; - switch (choice) { - case JDBC: - LOG.debug(">>>> setPersistenceAdapter to JDBC "); - adapter = new JDBCPersistenceAdapter(); - break; - case KahaDB: - LOG.debug(">>>> setPersistenceAdapter to KahaDB "); - adapter = new KahaDBPersistenceAdapter(); - break; - case LevelDB: - LOG.debug(">>>> setPersistenceAdapter to LevelDB "); - adapter = new LevelDBPersistenceAdapter(); - break; - case MEM: - LOG.debug(">>>> setPersistenceAdapter to MEM "); - adapter = new MemoryPersistenceAdapter(); - break; - } - broker.setPersistenceAdapter(adapter); - return adapter; - } -} - -class DurableSubscriptionOfflineTestListener implements MessageListener { - - private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionOfflineTestListener.class); - int count = 0; - String id = null; - - DurableSubscriptionOfflineTestListener() { - } - - DurableSubscriptionOfflineTestListener(String id) { - this.id = id; - } - - @Override - public void onMessage(javax.jms.Message message) { - count++; - if (id != null) { - try { - LOG.info(id + ", " + message.getJMSMessageID()); - } catch (Exception ignored) { - } - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionReactivationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionReactivationTest.java deleted file mode 100644 index b23e4dda5c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionReactivationTest.java +++ /dev/null @@ -1,98 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.Topic; -import javax.jms.TopicSubscriber; - -import junit.framework.Test; - -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; - -public class DurableSubscriptionReactivationTest extends EmbeddedBrokerTestSupport { - - public boolean keepDurableSubsActive; - - public void initCombosForTestReactivateKeepaliveSubscription() { - addCombinationValues("keepDurableSubsActive", new Object[]{Boolean.valueOf(true), Boolean.valueOf(false)}); - } - - public void testReactivateKeepaliveSubscription() throws Exception { - - Connection connection = createConnection(); - connection.setClientID("cliID"); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber subscriber = session.createDurableSubscriber((Topic) createDestination(), "subName"); - subscriber.close(); - connection.close(); - - connection = createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(createDestination()); - producer.send(session.createMessage()); - connection.close(); - - connection = createConnection(); - connection.setClientID("cliID"); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - subscriber = session.createDurableSubscriber((Topic) createDestination(), "subName"); - Message message = subscriber.receive(1 * 1000); - subscriber.close(); - connection.close(); - - assertNotNull("Message not received.", message); - } - - @Override - protected void setUp() throws Exception { - useTopic = true; - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService answer = super.createBroker(); - answer.setKeepDurableSubsActive(keepDurableSubsActive); - answer.setPersistenceAdapter(new JDBCPersistenceAdapter()); - answer.setDeleteAllMessagesOnStartup(true); - return answer; - } - - @Override - protected boolean isPersistent() { - return true; - } - - public static Test suite() { - return suite(DurableSubscriptionReactivationTest.class); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionRemoveOfflineTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionRemoveOfflineTest.java deleted file mode 100644 index e356a94cab..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionRemoveOfflineTest.java +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Session; -import javax.jms.Topic; -import javax.jms.TopicSubscriber; - -import junit.framework.Test; - -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.util.Wait; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DurableSubscriptionRemoveOfflineTest extends EmbeddedBrokerTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(DurableSubscriptionRemoveOfflineTest.class); - - @Override - protected void setUp() throws Exception { - useTopic = true; - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - } - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService answer = super.createBroker(); - answer.setOfflineDurableSubscriberTaskSchedule(3 * 1000); - answer.setOfflineDurableSubscriberTimeout(5 * 1000); - answer.setDeleteAllMessagesOnStartup(true); - return answer; - } - - protected BrokerService restartBroker() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - broker = null; - - broker = super.createBroker(); - broker.setOfflineDurableSubscriberTaskSchedule(3 * 1000); - broker.setOfflineDurableSubscriberTimeout(5 * 1000); - - broker.start(); - broker.waitUntilStarted(); - - return broker; - } - - public void testRemove() throws Exception { - Connection connection = createConnection(); - connection.setClientID("cliID"); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber subscriber = session.createDurableSubscriber((Topic) createDestination(), "subName"); - subscriber.close(); - connection.close(); - - assertTrue(Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return broker.getAdminView().getInactiveDurableTopicSubscribers().length == 0; - } - }, 15000)); - } - - public void testRemoveAfterRestart() throws Exception { - Connection connection = createConnection(); - connection.setClientID("cliID"); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber subscriber = session.createDurableSubscriber((Topic) createDestination(), "subName"); - subscriber.close(); - connection.close(); - - LOG.info("Broker restarting, wait for inactive cleanup afterwards."); - - restartBroker(); - - LOG.info("Broker restarted, wait for inactive cleanup now."); - - assertTrue(broker.getAdminView().getInactiveDurableTopicSubscribers().length == 1); - - assertTrue(Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return broker.getAdminView().getInactiveDurableTopicSubscribers().length == 0; - } - }, 20000)); - } - - @Override - protected boolean isPersistent() { - return true; - } - - public static Test suite() { - return suite(DurableSubscriptionRemoveOfflineTest.class); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionSelectorTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionSelectorTest.java deleted file mode 100644 index 7d7adb24f9..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionSelectorTest.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.activemq.usecases; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TopicSubscriber; -import javax.management.MBeanServer; -import java.lang.management.ManagementFactory; - -import junit.framework.Test; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.util.Wait; - -public class DurableSubscriptionSelectorTest extends org.apache.activemq.TestSupport { - - MBeanServer mbs; - BrokerService broker = null; - ActiveMQTopic topic; - - ActiveMQConnection consumerConnection = null, producerConnection = null; - Session producerSession; - MessageProducer producer; - - private int received = 0; - - public static Test suite() { - return suite(DurableSubscriptionSelectorTest.class); - } - - public void initCombosForTestSubscription() throws Exception { - this.addCombinationValues("defaultPersistenceAdapter", PersistenceAdapterChoice.values()); - } - - public void testSubscription() throws Exception { - openConsumer(); - for (int i = 0; i < 4000; i++) { - sendMessage(false); - } - Thread.sleep(1000); - - assertEquals("Invalid message received.", 0, received); - - closeProducer(); - closeConsumer(); - stopBroker(); - - startBroker(false); - openConsumer(); - - sendMessage(true); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() { - return received >= 1; - } - }, 10000); - - assertEquals("Message is not received.", 1, received); - - sendMessage(true); - Thread.sleep(100); - - assertEquals("Message is not received.", 2, received); - } - - private void openConsumer() throws Exception { - consumerConnection = (ActiveMQConnection) createConnection(); - consumerConnection.setClientID("cliID"); - consumerConnection.start(); - Session session = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - TopicSubscriber subscriber = session.createDurableSubscriber(topic, "subName", "filter=true", false); - - subscriber.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - received++; - } - }); - } - - private void closeConsumer() throws JMSException { - if (consumerConnection != null) - consumerConnection.close(); - consumerConnection = null; - } - - private void sendMessage(boolean filter) throws Exception { - if (producerConnection == null) { - producerConnection = (ActiveMQConnection) createConnection(); - producerConnection.start(); - producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = producerSession.createProducer(topic); - } - - Message message = producerSession.createMessage(); - message.setBooleanProperty("filter", filter); - producer.send(message); - } - - private void closeProducer() throws JMSException { - if (producerConnection != null) - producerConnection.close(); - producerConnection = null; - } - - private void startBroker(boolean deleteMessages) throws Exception { - broker = new BrokerService(); - broker.setBrokerName("test-broker"); - - if (deleteMessages) { - broker.setDeleteAllMessagesOnStartup(true); - } - setDefaultPersistenceAdapter(broker); - - /* use maxPageSize policy in place of always pulling from the broker in maxRows chunks - if (broker.getPersistenceAdapter() instanceof JDBCPersistenceAdapter) { - ((JDBCPersistenceAdapter)broker.getPersistenceAdapter()).setMaxRows(5000); - }*/ - - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setMaxPageSize(5000); - policyMap.setDefaultEntry(defaultEntry); - broker.setDestinationPolicy(policyMap); - - broker.start(); - } - - private void stopBroker() throws Exception { - if (broker != null) - broker.stop(); - broker = null; - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://test-broker?jms.watchTopicAdvisories=false&waitForStart=5000&create=false"); - } - - @Override - protected void setUp() throws Exception { - setAutoFail(true); - super.setUp(); - - startBroker(true); - topic = (ActiveMQTopic) createDestination(); - mbs = ManagementFactory.getPlatformMBeanServer(); - } - - @Override - protected void tearDown() throws Exception { - stopBroker(); - super.tearDown(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionTestSupport.java deleted file mode 100644 index fe4e94d96e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionTestSupport.java +++ /dev/null @@ -1,534 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.jms.Topic; -import javax.jms.TopicSubscriber; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ActiveMQSession; -import org.apache.activemq.TestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.store.PersistenceAdapter; - -/** - * - */ -public abstract class DurableSubscriptionTestSupport extends TestSupport { - - private Connection connection; - private Session session; - private TopicSubscriber consumer; - private MessageProducer producer; - private BrokerService broker; - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://durable-broker"); - } - - @Override - protected Connection createConnection() throws Exception { - Connection rc = super.createConnection(); - rc.setClientID(getName()); - return rc; - } - - @Override - protected void setUp() throws Exception { - createBroker(); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - destroyBroker(); - } - - protected void restartBroker() throws Exception { - destroyBroker(); - createRestartedBroker(); // retain stored messages - } - - private void createBroker() throws Exception { - broker = new BrokerService(); - broker.setBrokerName("durable-broker"); - broker.setDeleteAllMessagesOnStartup(true); - broker.setPersistenceAdapter(createPersistenceAdapter()); - broker.setPersistent(true); - broker.start(); - broker.waitUntilStarted(); - - connection = createConnection(); - } - - private void createRestartedBroker() throws Exception { - broker = new BrokerService(); - broker.setBrokerName("durable-broker"); - broker.setDeleteAllMessagesOnStartup(false); - broker.setPersistenceAdapter(createPersistenceAdapter()); - broker.setPersistent(true); - broker.start(); - broker.waitUntilStarted(); - - connection = createConnection(); - } - - private void destroyBroker() throws Exception { - if (connection != null) { - connection.close(); - } - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } - - protected abstract PersistenceAdapter createPersistenceAdapter() throws Exception; - - public void testMessageExpire() throws Exception { - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic("TestTopic"); - consumer = session.createDurableSubscriber(topic, "sub1"); - producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - producer.setTimeToLive(1000); - connection.start(); - - // Make sure it works when the durable sub is active. - producer.send(session.createTextMessage("Msg:1")); - assertTextMessageEquals("Msg:1", consumer.receive(1000)); - - consumer.close(); - - producer.send(session.createTextMessage("Msg:2")); - producer.send(session.createTextMessage("Msg:3")); - - consumer = session.createDurableSubscriber(topic, "sub1"); - - // Try to get the message. - assertTextMessageEquals("Msg:2", consumer.receive(1000)); - Thread.sleep(1000); - assertNull(consumer.receive(1000)); - } - - public void testUnsubscribeSubscription() throws Exception { - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic("TestTopic"); - consumer = session.createDurableSubscriber(topic, "sub1"); - producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - connection.start(); - - // Make sure it works when the durable sub is active. - producer.send(session.createTextMessage("Msg:1")); - assertTextMessageEquals("Msg:1", consumer.receive(5000)); - - // Deactivate the sub. - consumer.close(); - // Send a new message. - producer.send(session.createTextMessage("Msg:2")); - session.unsubscribe("sub1"); - - // Reopen the connection. - connection.close(); - connection = createConnection(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(topic); - connection.start(); - - // Activate the sub. - consumer = session.createDurableSubscriber(topic, "sub1"); - producer.send(session.createTextMessage("Msg:3")); - - // Try to get the message. - assertTextMessageEquals("Msg:3", consumer.receive(5000)); - } - - public void testInactiveDurableSubscriptionTwoConnections() throws Exception { - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic("TestTopic"); - consumer = session.createDurableSubscriber(topic, "sub1"); - producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - connection.start(); - - // Make sure it works when the durable sub is active. - producer.send(session.createTextMessage("Msg:1")); - assertTextMessageEquals("Msg:1", consumer.receive(5000)); - - // Deactivate the sub. - consumer.close(); - - // Send a new message. - producer.send(session.createTextMessage("Msg:2")); - - // Reopen the connection. - connection.close(); - connection = createConnection(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - connection.start(); - - // Activate the sub. - consumer = session.createDurableSubscriber(topic, "sub1"); - - // Try to get the message. - assertTextMessageEquals("Msg:2", consumer.receive(5000)); - } - - public void testInactiveDurableSubscriptionBrokerRestart() throws Exception { - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic("TestTopic"); - consumer = session.createDurableSubscriber(topic, "sub1"); - producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - connection.start(); - - // Make sure it works when the durable sub is active. - producer.send(session.createTextMessage("Msg:1")); - assertTextMessageEquals("Msg:1", consumer.receive(5000)); - - // Deactivate the sub. - consumer.close(); - - // Send a new message. - producer.send(session.createTextMessage("Msg:2")); - - // Reopen the connection. - restartBroker(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - connection.start(); - - // Activate the sub. - consumer = session.createDurableSubscriber(topic, "sub1"); - - // Try to get the message. - assertTextMessageEquals("Msg:2", consumer.receive(5000)); - assertNull(consumer.receive(5000)); - } - - public void testDurableSubscriptionBrokerRestart() throws Exception { - - // Create the durable sub. - connection.start(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - - // Ensure that consumer will receive messages sent before it was created - Topic topic = session.createTopic("TestTopic?consumer.retroactive=true"); - consumer = session.createDurableSubscriber(topic, "sub1"); - - producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - producer.send(session.createTextMessage("Msg:1")); - assertTextMessageEquals("Msg:1", consumer.receive(5000)); - - // Make sure cleanup kicks in - Thread.sleep(1000); - - // Restart the broker. - restartBroker(); - } - - public void testDurableSubscriptionPersistsPastBrokerRestart() throws Exception { - - // Create the durable sub. - connection.start(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - - // Ensure that consumer will receive messages sent before it was created - Topic topic = session.createTopic("TestTopic?consumer.retroactive=true"); - consumer = session.createDurableSubscriber(topic, "sub1"); - - // Restart the broker. - restartBroker(); - - // Reconnection - connection.start(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - - // Make sure it works when the durable sub is active. - producer.send(session.createTextMessage("Msg:1")); - - // Activate the sub. - consumer = session.createDurableSubscriber(topic, "sub1"); - - // Send a new message. - producer.send(session.createTextMessage("Msg:2")); - - // Try to get the message. - assertTextMessageEquals("Msg:1", consumer.receive(5000)); - assertTextMessageEquals("Msg:2", consumer.receive(5000)); - - assertNull(consumer.receive(5000)); - } - - public void testDurableSubscriptionRetroactive() throws Exception { - - // Create the durable sub. - connection.start(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - - Topic topic = session.createTopic("TestTopic?consumer.retroactive=true"); - consumer = session.createDurableSubscriber(topic, "sub1"); - connection.close(); - - // Produce - connection = createConnection(); - connection.start(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - producer.send(session.createTextMessage("Msg:1")); - - restartBroker(); - - // connect second durable to pick up retroactive message - connection.start(); - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - consumer = session.createDurableSubscriber(topic, "sub2"); - - // Try to get the message. - assertTextMessageEquals("Msg:1", consumer.receive(5000)); - assertNull(consumer.receive(2000)); - } - - public void testDurableSubscriptionRollbackRedeliver() throws Exception { - - // Create the durable sub. - connection.start(); - - session = connection.createSession(true, javax.jms.Session.SESSION_TRANSACTED); - Topic topic = session.createTopic("TestTopic"); - consumer = session.createDurableSubscriber(topic, "sub1"); - - Session producerSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - producer = producerSession.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - - producer.send(session.createTextMessage("Msg:1")); - - // receive and rollback - assertTextMessageEquals("Msg:1", consumer.receive(5000)); - session.rollback(); - consumer.close(); - session.close(); - - session = connection.createSession(true, javax.jms.Session.SESSION_TRANSACTED); - - // Ensure that consumer will receive messages sent and rolled back - consumer = session.createDurableSubscriber(topic, "sub1"); - - assertTextMessageEquals("Msg:1", consumer.receive(5000)); - session.commit(); - - assertNull(consumer.receive(5000)); - } - - public void xtestInactiveDurableSubscriptionOneConnection() throws Exception { - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic("TestTopic"); - consumer = session.createDurableSubscriber(topic, "sub1"); - producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - connection.start(); - - // Make sure it works when the durable sub is active. - producer.send(session.createTextMessage("Msg:1")); - assertTextMessageEquals("Msg:1", consumer.receive(5000)); - - // Deactivate the sub. - consumer.close(); - - // Send a new message. - producer.send(session.createTextMessage("Msg:2")); - - // Activate the sub. - consumer = session.createDurableSubscriber(topic, "sub1"); - - // Try to get the message. - assertTextMessageEquals("Msg:2", consumer.receive(5000)); - } - - public void testSelectorChange() throws Exception { - session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic("TestTopic"); - consumer = session.createDurableSubscriber(topic, "sub1", "color='red'", false); - producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - connection.start(); - - // Make sure it works when the durable sub is active. - TextMessage msg = session.createTextMessage(); - msg.setText("Msg:1"); - msg.setStringProperty("color", "blue"); - producer.send(msg); - msg.setText("Msg:2"); - msg.setStringProperty("color", "red"); - producer.send(msg); - - assertTextMessageEquals("Msg:2", consumer.receive(5000)); - - // Change the subscription - consumer.close(); - consumer = session.createDurableSubscriber(topic, "sub1", "color='blue'", false); - - // Send a new message. - msg.setText("Msg:3"); - msg.setStringProperty("color", "red"); - producer.send(msg); - msg.setText("Msg:4"); - msg.setStringProperty("color", "blue"); - producer.send(msg); - - // Try to get the message. - assertTextMessageEquals("Msg:4", consumer.receive(5000)); - } - - public void testDurableSubWorksInNewSession() throws JMSException { - - // Create the consumer. - connection.start(); - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Topic topic = session.createTopic("topic-" + getName()); - MessageConsumer consumer = session.createDurableSubscriber(topic, "sub1"); - // Drain any messages that may already be in the sub - while (consumer.receive(1000) != null) { - } - - // See if the durable sub works in a new session. - session.close(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - - // Send a Message that should be added to the durable sub. - MessageProducer producer = createProducer(session, topic); - producer.send(session.createTextMessage("Message 1")); - - // Activate the durable sub now. And receive the message. - consumer = session.createDurableSubscriber(topic, "sub1"); - Message msg = consumer.receive(1000); - assertNotNull(msg); - assertEquals("Message 1", ((TextMessage) msg).getText()); - } - - public void testDurableSubWorksInNewConnection() throws Exception { - - // Create the consumer. - connection.start(); - Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Topic topic = session.createTopic("topic-" + getName()); - MessageConsumer consumer = session.createDurableSubscriber(topic, "sub1"); - // Drain any messages that may already be in the sub - while (consumer.receive(1000) != null) { - } - - // See if the durable sub works in a new connection. - // The embedded broker shuts down when its connections are closed. - // So we open the new connection before the old one is closed. - connection.close(); - connection = createConnection(); - connection.start(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - - // Send a Message that should be added to the durable sub. - MessageProducer producer = createProducer(session, topic); - producer.send(session.createTextMessage("Message 1")); - - // Activate the durable sub now. And receive the message. - consumer = session.createDurableSubscriber(topic, "sub1"); - Message msg = consumer.receive(1000); - assertNotNull(msg); - assertEquals("Message 1", ((TextMessage) msg).getText()); - } - - public void testIndividualAckWithDurableSubs() throws Exception { - // Create the consumer. - connection.start(); - - Session session = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE); - Topic topic = session.createTopic("topic-" + getName()); - MessageConsumer consumer = session.createDurableSubscriber(topic, "sub1"); - // Drain any messages that may already be in the sub - while (consumer.receive(1000) != null) { - } - consumer.close(); - - MessageProducer producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - producer.send(session.createTextMessage("Message 1")); - producer.send(session.createTextMessage("Message 2")); - producer.send(session.createTextMessage("Message 3")); - producer.close(); - - connection.close(); - connection = createConnection(); - connection.start(); - - session = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE); - consumer = session.createDurableSubscriber(topic, "sub1"); - - Message message = null; - for (int i = 0; i < 3; ++i) { - message = consumer.receive(5000); - assertNotNull(message); - assertEquals("Message " + (i + 1), ((TextMessage) message).getText()); - } - - message.acknowledge(); - - connection.close(); - connection = createConnection(); - connection.start(); - - session = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE); - consumer = session.createDurableSubscriber(topic, "sub1"); - - for (int i = 0; i < 2; ++i) { - message = consumer.receive(5000); - assertNotNull(message); - assertEquals("Message " + (i + 1), ((TextMessage) message).getText()); - } - } - - private MessageProducer createProducer(Session session, Destination queue) throws JMSException { - MessageProducer producer = session.createProducer(queue); - producer.setDeliveryMode(getDeliveryMode()); - return producer; - } - - protected int getDeliveryMode() { - return DeliveryMode.PERSISTENT; - } - - private void assertTextMessageEquals(String string, Message message) throws JMSException { - assertNotNull("Message was null", message); - assertTrue("Message is not a TextMessage", message instanceof TextMessage); - assertEquals(string, ((TextMessage) message).getText()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionUnsubscribeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionUnsubscribeTest.java deleted file mode 100644 index 14d2b64b86..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableSubscriptionUnsubscribeTest.java +++ /dev/null @@ -1,341 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.Session; -import javax.management.InstanceNotFoundException; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; -import java.io.File; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.TestSupport; -import org.apache.activemq.advisory.AdvisorySupport; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.ConnectionContext; -import org.apache.activemq.broker.jmx.DurableSubscriptionViewMBean; -import org.apache.activemq.broker.region.Destination; -import org.apache.activemq.broker.region.DurableTopicSubscription; -import org.apache.activemq.broker.region.Subscription; -import org.apache.activemq.command.ActiveMQMessage; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.command.RemoveSubscriptionInfo; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; - -public class DurableSubscriptionUnsubscribeTest extends TestSupport { - - BrokerService broker = null; - Connection connection = null; - ActiveMQTopic topic; - - public void testJMXSubscriptionUnsubscribe() throws Exception { - doJMXUnsubscribe(false); - } - - public void testJMXSubscriptionUnsubscribeWithRestart() throws Exception { - doJMXUnsubscribe(true); - } - - public void testConnectionSubscriptionUnsubscribe() throws Exception { - doConnectionUnsubscribe(false); - } - - public void testConnectionSubscriptionUnsubscribeWithRestart() throws Exception { - doConnectionUnsubscribe(true); - } - - public void testDirectSubscriptionUnsubscribe() throws Exception { - doDirectUnsubscribe(false); - } - - public void testDirectubscriptionUnsubscribeWithRestart() throws Exception { - doDirectUnsubscribe(true); - } - - public void doJMXUnsubscribe(boolean restart) throws Exception { - createSubscriptions(); - createAdvisorySubscription(); - - Thread.sleep(1000); - assertCount(100, 0); - - if (restart) { - restartBroker(); - createAdvisorySubscription(); - assertCount(100, 0); - } - - ObjectName[] subs = broker.getAdminView().getInactiveDurableTopicSubscribers(); - - for (int i = 0; i < subs.length; i++) { - ObjectName subName = subs[i]; - DurableSubscriptionViewMBean sub = (DurableSubscriptionViewMBean) broker.getManagementContext().newProxyInstance(subName, DurableSubscriptionViewMBean.class, true); - sub.destroy(); - - if (i % 20 == 0) { - Thread.sleep(1000); - assertCount(100 - i - 1, 0); - } - } - - Thread.sleep(1000); - assertCount(0, 0); - - if (restart) { - restartBroker(); - createAdvisorySubscription(); - assertCount(0, 0); - } - } - - public void doConnectionUnsubscribe(boolean restart) throws Exception { - createSubscriptions(); - createAdvisorySubscription(); - - Thread.sleep(1000); - assertCount(100, 0); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId1"); - - Thread.sleep(1000); - assertCount(100, 1); - - Session session2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session2.createDurableSubscriber(topic, "SubsId2"); - - Thread.sleep(1000); - assertCount(100, 2); - - session.close(); - - Thread.sleep(1000); - assertCount(100, 1); - - session2.close(); - - Thread.sleep(1000); - assertCount(100, 0); - - if (restart) { - restartBroker(); - createAdvisorySubscription(); - assertCount(100, 0); - } - - for (int i = 0; i < 100; i++) { - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.unsubscribe("SubsId" + i); - session.close(); - - if (i % 20 == 0) { - Thread.sleep(1000); - assertCount(100 - i - 1, 0); - } - } - - Thread.sleep(1000); - assertCount(0, 0); - - if (restart) { - restartBroker(); - createAdvisorySubscription(); - assertCount(0, 0); - } - } - - public void doDirectUnsubscribe(boolean restart) throws Exception { - createSubscriptions(); - createAdvisorySubscription(); - - Thread.sleep(1000); - assertCount(100, 0); - - if (restart) { - restartBroker(); - createAdvisorySubscription(); - assertCount(100, 0); - } - - for (int i = 0; i < 100; i++) { - RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); - info.setClientId(getName()); - info.setSubscriptionName("SubsId" + i); - ConnectionContext context = new ConnectionContext(); - context.setBroker(broker.getRegionBroker()); - context.setClientId(getName()); - broker.getBroker().removeSubscription(context, info); - - if (i % 20 == 0) { - Thread.sleep(1000); - assertCount(100 - i - 1, 0); - } - } - - assertCount(0, 0); - - if (restart) { - restartBroker(); - createAdvisorySubscription(); - assertCount(0, 0); - } - } - - private void createSubscriptions() throws Exception { - for (int i = 0; i < 100; i++) { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId" + i); - session.close(); - } - } - - private final AtomicInteger advisories = new AtomicInteger(0); - - private void createAdvisorySubscription() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer advisoryConsumer = session.createConsumer(AdvisorySupport.getConsumerAdvisoryTopic(topic)); - advisoryConsumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - if (((ActiveMQMessage) message).getDataStructure() instanceof RemoveSubscriptionInfo) { - advisories.incrementAndGet(); - } - } - }); - } - - private void assertCount(int all, int active) throws Exception { - int inactive = all - active; - - // broker check - Destination destination = broker.getDestination(topic); - List subs = destination.getConsumers(); - int cActive = 0, cInactive = 0; - for (Subscription sub : subs) { - if (sub instanceof DurableTopicSubscription) { - DurableTopicSubscription durable = (DurableTopicSubscription) sub; - if (durable.isActive()) - cActive++; - else - cInactive++; - } - } - assertEquals(active, cActive); - assertEquals(inactive, cInactive); - - // admin view - ObjectName[] subscriptions = broker.getAdminView().getDurableTopicSubscribers(); - assertEquals(active, subscriptions.length); - subscriptions = broker.getAdminView().getInactiveDurableTopicSubscribers(); - assertEquals(inactive, subscriptions.length); - - // check the strange false MBean - if (all == 0) - assertEquals(0, countMBean()); - - // check if we got all advisories - assertEquals(100, all + advisories.get()); - } - - private int countMBean() throws MalformedObjectNameException, InstanceNotFoundException { - int count = 0; - for (int i = 0; i < 100; i++) { - String name = "org.apache.activemq:BrokerName=" + getName() + ",Type=Subscription,active=false,name=" + getName() + "_SubsId" + i; - ObjectName sub = new ObjectName(name); - try { - broker.getManagementContext().getObjectInstance(sub); - count++; - } catch (InstanceNotFoundException ignore) { - // this should happen - } - } - return count; - } - - private void startBroker(boolean deleteMessages) throws Exception { - broker = BrokerFactory.createBroker("broker:(vm://" + getName() + ")"); - broker.setUseJmx(true); - broker.getManagementContext().setCreateConnector(false); - broker.setBrokerName(getName()); - - broker.setPersistent(true); - KahaDBPersistenceAdapter persistenceAdapter = new KahaDBPersistenceAdapter(); - persistenceAdapter.setDirectory(new File("activemq-data/" + getName())); - broker.setPersistenceAdapter(persistenceAdapter); - if (deleteMessages) { - broker.setDeleteAllMessagesOnStartup(true); - } - - broker.setKeepDurableSubsActive(true); - - broker.start(); - broker.waitUntilStarted(); - - connection = createConnection(); - } - - private void stopBroker() throws Exception { - if (connection != null) - connection.close(); - connection = null; - - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - broker = null; - } - - private void restartBroker() throws Exception { - stopBroker(); - startBroker(false); - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://" + getName() + "?waitForStart=5000&create=false"); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - - topic = (ActiveMQTopic) createDestination(); - startBroker(true); - } - - @Override - protected void tearDown() throws Exception { - stopBroker(); - super.tearDown(); - } - - @Override - protected Connection createConnection() throws Exception { - Connection rc = super.createConnection(); - rc.setClientID(getName()); - rc.start(); - return rc; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableUnsubscribeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableUnsubscribeTest.java deleted file mode 100644 index ff38aa2828..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/DurableUnsubscribeTest.java +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.management.MBeanServer; -import javax.management.ObjectName; -import java.lang.management.ManagementFactory; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.Destination; -import org.apache.activemq.command.ActiveMQTopic; - -public class DurableUnsubscribeTest extends org.apache.activemq.TestSupport { - - private BrokerService broker; - private Connection connection; - private ActiveMQTopic topic; - - public void testUnsubscribe() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId"); - session.close(); - - Destination d = broker.getDestination(topic); - assertEquals("Subscription is missing.", 1, d.getConsumers().size()); - - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(topic); - for (int i = 0; i < 1000; i++) { - producer.send(session.createTextMessage("text")); - } - - Thread.sleep(1000); - - session.unsubscribe("SubsId"); - session.close(); - - assertEquals("Subscription exists.", 0, d.getConsumers().size()); - } - - public void testDestroy() throws Exception { - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId2"); - session.close(); - - connection.close(); - connection = null; - Thread.sleep(1000); - - Destination d = broker.getDestination(topic); - assertEquals("Subscription is missing.", 1, d.getConsumers().size()); - - MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); - ObjectName[] subNames = broker.getAdminView().getInactiveDurableTopicSubscribers(); - mbs.invoke(subNames[0], "destroy", new Object[0], new String[0]); - - assertEquals("Subscription exists.", 0, d.getConsumers().size()); - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://" + getName()); - } - - @Override - protected Connection createConnection() throws Exception { - Connection rc = super.createConnection(); - rc.setClientID(getName()); - return rc; - } - - @Override - protected void setUp() throws Exception { - topic = (ActiveMQTopic) createDestination(); - createBroker(); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - destroyBroker(); - } - - private void createBroker() throws Exception { - broker = BrokerFactory.createBroker("broker:(vm://localhost)"); - //broker.setPersistent(false); - broker.setUseJmx(true); - broker.setBrokerName(getName()); - broker.deleteAllMessages(); - broker.start(); - - connection = createConnection(); - } - - private void destroyBroker() throws Exception { - if (connection != null) - connection.close(); - if (broker != null) - broker.stop(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExceptionListenerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExceptionListenerTest.java deleted file mode 100644 index eab3ed3f4b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExceptionListenerTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.ExceptionListener; -import javax.jms.JMSException; -import javax.jms.JMSSecurityException; -import javax.jms.Session; -import java.net.URI; -import java.util.ArrayList; -import java.util.LinkedList; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ConnectionFailedException; -import org.apache.activemq.broker.BrokerPlugin; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.security.SimpleAuthenticationPlugin; -import org.apache.activemq.util.Wait; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -/** - * @author Oliver Belikan - */ -public class ExceptionListenerTest implements ExceptionListener { - - private static final Logger LOG = LoggerFactory.getLogger(ExceptionListenerTest.class); - BrokerService brokerService; - URI brokerUri; - LinkedList exceptionsViaListener = new LinkedList<>(); - - @Before - public void startBroker() throws Exception { - brokerService = new BrokerService(); - brokerService.setAdvisorySupport(false); - brokerService.setUseJmx(false); - brokerService.setPersistent(false); - brokerService.setPlugins(new BrokerPlugin[]{new SimpleAuthenticationPlugin(new ArrayList())}); - brokerUri = brokerService.addConnector("tcp://0.0.0.0:0").getConnectUri(); - brokerService.start(); - } - - @After - public void stopBroker() throws Exception { - exceptionsViaListener.clear(); - if (brokerService != null) { - brokerService.stop(); - } - } - - @Test - public void fireOnSecurityException() throws Exception { - doFireOnSecurityException(new ActiveMQConnectionFactory(brokerUri)); - } - - @Test - public void fireOnSecurityExceptionFailover() throws Exception { - doFireOnSecurityException(new ActiveMQConnectionFactory("failover://" + brokerUri)); - } - - public void doFireOnSecurityException(ActiveMQConnectionFactory factory) throws Exception { - factory.setWatchTopicAdvisories(false); - Connection connection = factory.createConnection(); - connection.setExceptionListener(this); - - try { - connection.start(); - fail("Expect securityException"); - } catch (JMSSecurityException expected) { - expected.printStackTrace(); - assertTrue("nested security exception: " + expected, expected.getCause() instanceof SecurityException); - } - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return !exceptionsViaListener.isEmpty(); - } - }); - Throwable expected = exceptionsViaListener.getFirst(); - assertNotNull(expected); - assertNotNull(expected.getCause()); - - assertTrue("expected exception: " + expected, expected.getCause().getCause() instanceof SecurityException); - - try { - connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - fail("Expect error b/c connection is auto closed on security exception above"); - } catch (ConnectionFailedException e) { - } - } - - @Override - public void onException(JMSException e) { - LOG.info("onException:" + e, new Throwable("FromHere")); - exceptionsViaListener.add(e); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExpiredMessagesTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExpiredMessagesTest.java deleted file mode 100644 index 2df345fc4a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExpiredMessagesTest.java +++ /dev/null @@ -1,306 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.util.concurrent.atomic.AtomicLong; - -import junit.framework.Test; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.CombinationTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.DestinationStatistics; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.broker.region.policy.VMPendingQueueMessageStoragePolicy; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.store.memory.MemoryPersistenceAdapter; -import org.apache.activemq.util.Wait; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.apache.activemq.TestSupport.getDestination; -import static org.apache.activemq.TestSupport.getDestinationStatistics; - -public class ExpiredMessagesTest extends CombinationTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(ExpiredMessagesTest.class); - - BrokerService broker; - Connection connection; - Session session; - MessageProducer producer; - MessageConsumer consumer; - public ActiveMQDestination destination = new ActiveMQQueue("test"); - public ActiveMQDestination dlqDestination = new ActiveMQQueue("ActiveMQ.DLQ"); - public boolean useTextMessage = true; - public boolean useVMCursor = true; - protected String brokerUri; - - public static Test suite() { - return suite(ExpiredMessagesTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - @Override - protected void setUp() throws Exception { - final boolean deleteAllMessages = true; - broker = createBroker(deleteAllMessages, 100); - brokerUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - } - - @Override - protected void tearDown() throws Exception { - connection.stop(); - broker.stop(); - broker.waitUntilStopped(); - } - - public void testExpiredMessages() throws Exception { - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerUri); - connection = factory.createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(destination); - producer.setTimeToLive(100); - consumer = session.createConsumer(destination); - connection.start(); - final AtomicLong received = new AtomicLong(); - - Thread consumerThread = new Thread("Consumer Thread") { - @Override - public void run() { - long start = System.currentTimeMillis(); - try { - long end = System.currentTimeMillis(); - while (end - start < 3000) { - if (consumer.receive(1000) != null) { - received.incrementAndGet(); - } - Thread.sleep(100); - end = System.currentTimeMillis(); - } - consumer.close(); - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - }; - - consumerThread.start(); - - final int numMessagesToSend = 10000; - Thread producingThread = new Thread("Producing Thread") { - @Override - public void run() { - try { - int i = 0; - while (i++ < numMessagesToSend) { - producer.send(session.createTextMessage("test")); - } - producer.close(); - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - }; - - producingThread.start(); - - consumerThread.join(); - producingThread.join(); - session.close(); - - final DestinationStatistics view = getDestinationStatistics(broker, destination); - - // wait for all to inflight to expire - assertTrue("all inflight messages expired ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return view.getInflight().getCount() == 0; - } - })); - assertEquals("Wrong inFlightCount: ", 0, view.getInflight().getCount()); - - LOG.info("Stats: received: " + received.get() + ", enqueues: " + view.getEnqueues().getCount() + ", dequeues: " + view.getDequeues().getCount() + ", dispatched: " + view.getDispatched().getCount() + ", inflight: " + view.getInflight().getCount() + ", expiries: " + view.getExpired().getCount()); - - // wait for all sent to get delivered and expire - assertTrue("all sent messages expired ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - long oldEnqueues = view.getEnqueues().getCount(); - Thread.sleep(200); - LOG.info("Stats: received: " + received.get() + ", size= " + view.getMessages().getCount() + ", enqueues: " + view.getDequeues().getCount() + ", dequeues: " + view.getDequeues().getCount() + ", dispatched: " + view.getDispatched().getCount() + ", inflight: " + view.getInflight().getCount() + ", expiries: " + view.getExpired().getCount()); - return oldEnqueues == view.getEnqueues().getCount(); - } - }, 60 * 1000)); - - LOG.info("Stats: received: " + received.get() + ", size= " + view.getMessages().getCount() + ", enqueues: " + view.getEnqueues().getCount() + ", dequeues: " + view.getDequeues().getCount() + ", dispatched: " + view.getDispatched().getCount() + ", inflight: " + view.getInflight().getCount() + ", expiries: " + view.getExpired().getCount()); - - assertTrue("got at least what did not expire", received.get() >= view.getDequeues().getCount() - view.getExpired().getCount()); - - assertTrue("all messages expired - queue size gone to zero " + view.getMessages().getCount(), Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Stats: received: " + received.get() + ", size= " + view.getMessages().getCount() + ", enqueues: " + view.getEnqueues().getCount() + ", dequeues: " + view.getDequeues().getCount() + ", dispatched: " + view.getDispatched().getCount() + ", inflight: " + view.getInflight().getCount() + ", expiries: " + view.getExpired().getCount()); - return view.getMessages().getCount() == 0; - } - })); - - final long expiredBeforeEnqueue = numMessagesToSend - view.getEnqueues().getCount(); - final long totalExpiredCount = view.getExpired().getCount() + expiredBeforeEnqueue; - - final DestinationStatistics dlqView = getDestinationStatistics(broker, dlqDestination); - LOG.info("DLQ stats: size= " + dlqView.getMessages().getCount() + ", enqueues: " + dlqView.getDequeues().getCount() + ", dequeues: " + dlqView.getDequeues().getCount() + ", dispatched: " + dlqView.getDispatched().getCount() + ", inflight: " + dlqView.getInflight().getCount() + ", expiries: " + dlqView.getExpired().getCount()); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return totalExpiredCount == dlqView.getMessages().getCount(); - } - }); - assertEquals("dlq contains all expired", totalExpiredCount, dlqView.getMessages().getCount()); - - // memory check - assertEquals("memory usage is back to duck egg", 0, getDestination(broker, destination).getMemoryUsage().getPercentUsage()); - assertTrue("memory usage is increased ", 0 < getDestination(broker, dlqDestination).getMemoryUsage().getUsage()); - - // verify DLQ - MessageConsumer dlqConsumer = createDlqConsumer(connection); - final DLQListener dlqListener = new DLQListener(); - dlqConsumer.setMessageListener(dlqListener); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return totalExpiredCount == dlqListener.count; - } - }, 60 * 1000); - - assertEquals("dlq returned all expired", dlqListener.count, totalExpiredCount); - } - - class DLQListener implements MessageListener { - - int count = 0; - - @Override - public void onMessage(Message message) { - count++; - } - - } - - private MessageConsumer createDlqConsumer(Connection connection) throws Exception { - return connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createConsumer(dlqDestination); - } - - public void initCombosForTestRecoverExpiredMessages() { - addCombinationValues("useVMCursor", new Object[]{Boolean.TRUE, Boolean.FALSE}); - } - - public void testRecoverExpiredMessages() throws Exception { - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("failover://" + brokerUri); - connection = factory.createConnection(); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(destination); - producer.setTimeToLive(2000); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - - Thread producingThread = new Thread("Producing Thread") { - @Override - public void run() { - try { - int i = 0; - while (i++ < 1000) { - Message message = useTextMessage ? session.createTextMessage("test") : session.createObjectMessage("test"); - producer.send(message); - } - producer.close(); - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - }; - - producingThread.start(); - producingThread.join(); - - DestinationStatistics view = getDestinationStatistics(broker, destination); - LOG.info("Stats: size: " + view.getMessages().getCount() + ", enqueues: " + view.getEnqueues().getCount() + ", dequeues: " + view.getDequeues().getCount() + ", dispatched: " + view.getDispatched().getCount() + ", inflight: " + view.getInflight().getCount() + ", expiries: " + view.getExpired().getCount()); - - LOG.info("stopping broker"); - broker.stop(); - broker.waitUntilStopped(); - - Thread.sleep(5000); - - LOG.info("recovering broker"); - final boolean deleteAllMessages = false; - broker = createBroker(deleteAllMessages, 5000); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - DestinationStatistics view = getDestinationStatistics(broker, destination); - LOG.info("Stats: size: " + view.getMessages().getCount() + ", enqueues: " + view.getEnqueues().getCount() + ", dequeues: " + view.getDequeues().getCount() + ", dispatched: " + view.getDispatched().getCount() + ", inflight: " + view.getInflight().getCount() + ", expiries: " + view.getExpired().getCount()); - - return view.getMessages().getCount() == 0; - } - }); - - view = getDestinationStatistics(broker, destination); - assertEquals("Expect empty queue, QueueSize: ", 0, view.getMessages().getCount()); - assertEquals("all dequeues were expired", view.getDequeues().getCount(), view.getExpired().getCount()); - } - - private BrokerService createBroker(boolean deleteAllMessages, long expireMessagesPeriod) throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("localhost"); - broker.setDestinations(new ActiveMQDestination[]{destination}); - broker.setPersistenceAdapter(new MemoryPersistenceAdapter()); - - PolicyEntry defaultPolicy = new PolicyEntry(); - if (useVMCursor) { - defaultPolicy.setPendingQueuePolicy(new VMPendingQueueMessageStoragePolicy()); - } - defaultPolicy.setExpireMessagesPeriod(expireMessagesPeriod); - defaultPolicy.setMaxExpirePageSize(1200); - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(defaultPolicy); - broker.setDestinationPolicy(policyMap); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - broker.addConnector("tcp://localhost:0"); - broker.start(); - broker.waitUntilStarted(); - return broker; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExpiredMessagesWithNoConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExpiredMessagesWithNoConsumerTest.java deleted file mode 100644 index e55c9f1923..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ExpiredMessagesWithNoConsumerTest.java +++ /dev/null @@ -1,585 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.Topic; -import javax.jms.TopicSubscriber; -import javax.management.ObjectName; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - -import junit.framework.Test; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.CombinationTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.jmx.DestinationViewMBean; -import org.apache.activemq.broker.region.policy.FilePendingQueueMessageStoragePolicy; -import org.apache.activemq.broker.region.policy.PendingQueueMessageStoragePolicy; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.broker.region.policy.VMPendingQueueMessageStoragePolicy; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.util.Wait; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ExpiredMessagesWithNoConsumerTest extends CombinationTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(ExpiredMessagesWithNoConsumerTest.class); - - private final ActiveMQDestination destination = new ActiveMQQueue("test"); - - private boolean optimizedDispatch = true; - private PendingQueueMessageStoragePolicy pendingQueuePolicy; - - private BrokerService broker; - private String connectionUri; - private Connection connection; - private Session session; - private MessageProducer producer; - - public static Test suite() { - return suite(ExpiredMessagesWithNoConsumerTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - protected void createBrokerWithMemoryLimit() throws Exception { - createBrokerWithMemoryLimit(800); - } - - protected void createBrokerWithMemoryLimit(int expireMessagesPeriod) throws Exception { - doCreateBroker(true, expireMessagesPeriod); - } - - protected void createBroker() throws Exception { - doCreateBroker(false, 800); - } - - private void doCreateBroker(boolean memoryLimit, int expireMessagesPeriod) throws Exception { - broker = new BrokerService(); - broker.setBrokerName("localhost"); - broker.setUseJmx(true); - broker.setDeleteAllMessagesOnStartup(true); - broker.addConnector("tcp://localhost:0"); - - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setOptimizedDispatch(optimizedDispatch); - defaultEntry.setExpireMessagesPeriod(expireMessagesPeriod); - defaultEntry.setMaxExpirePageSize(800); - - defaultEntry.setPendingQueuePolicy(pendingQueuePolicy); - - if (memoryLimit) { - // so memory is not consumed by DLQ turn if off - defaultEntry.setDeadLetterStrategy(null); - defaultEntry.setMemoryLimit(200 * 1000); - } - - policyMap.setDefaultEntry(defaultEntry); - - broker.setDestinationPolicy(policyMap); - broker.start(); - broker.waitUntilStarted(); - - connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - } - - public void testExpiredNonPersistentMessagesWithNoConsumer() throws Exception { - - createBrokerWithMemoryLimit(2000); - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - connection = factory.createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(destination); - producer.setTimeToLive(1000); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - connection.start(); - final long sendCount = 2000; - - final Thread producingThread = new Thread("Producing Thread") { - @Override - public void run() { - try { - int i = 0; - long tStamp = System.currentTimeMillis(); - while (i++ < sendCount) { - producer.send(session.createTextMessage("test")); - if (i % 100 == 0) { - LOG.info("sent: " + i + " @ " + ((System.currentTimeMillis() - tStamp) / 100) + "m/ms"); - tStamp = System.currentTimeMillis(); - } - - if (135 == i) { - // allow pending messages to expire, before usage limit kicks in to flush them - TimeUnit.SECONDS.sleep(5); - } - } - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - }; - - producingThread.start(); - - assertTrue("producer failed to complete within allocated time", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - producingThread.join(TimeUnit.SECONDS.toMillis(3000)); - return !producingThread.isAlive(); - } - })); - - TimeUnit.SECONDS.sleep(5); - - final DestinationViewMBean view = createView(destination); - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - try { - LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize()); - return view.getDequeueCount() != 0 && view.getDequeueCount() == view.getExpiredCount() && view.getDequeueCount() == view.getEnqueueCount() && view.getQueueSize() == 0; - } catch (Exception ignored) { - LOG.info(ignored.toString()); - } - return false; - } - }, Wait.MAX_WAIT_MILLIS * 10); - LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize()); - - assertEquals("memory usage doesn't go to duck egg", 0, view.getMemoryPercentUsage()); - assertEquals("0 queue", 0, view.getQueueSize()); - } - - public void initCombosForTestExpiredMessagesWithNoConsumer() { - addCombinationValues("optimizedDispatch", new Object[]{Boolean.TRUE, Boolean.FALSE}); - addCombinationValues("pendingQueuePolicy", new Object[]{null, new VMPendingQueueMessageStoragePolicy(), new FilePendingQueueMessageStoragePolicy()}); - } - - public void testExpiredMessagesWithNoConsumer() throws Exception { - - createBrokerWithMemoryLimit(); - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - connection = factory.createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - producer = session.createProducer(destination); - producer.setTimeToLive(1000); - connection.start(); - final long sendCount = 2000; - - final Thread producingThread = new Thread("Producing Thread") { - @Override - public void run() { - try { - int i = 0; - long tStamp = System.currentTimeMillis(); - while (i++ < sendCount) { - producer.send(session.createTextMessage("test")); - if (i % 100 == 0) { - LOG.info("sent: " + i + " @ " + ((System.currentTimeMillis() - tStamp) / 100) + "m/ms"); - tStamp = System.currentTimeMillis(); - } - } - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - }; - - producingThread.start(); - - assertTrue("producer failed to complete within allocated time", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - producingThread.join(TimeUnit.SECONDS.toMillis(3000)); - return !producingThread.isAlive(); - } - })); - - final DestinationViewMBean view = createView(destination); - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize()); - return sendCount == view.getExpiredCount(); - } - }, Wait.MAX_WAIT_MILLIS * 10); - LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize()); - - assertEquals("Not all sent messages have expired", sendCount, view.getExpiredCount()); - assertEquals("memory usage doesn't go to duck egg", 0, view.getMemoryPercentUsage()); - } - - // first ack delivered after expiry - public void testExpiredMessagesWithVerySlowConsumer() throws Exception { - createBroker(); - final long queuePrefetch = 5; - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri + "?jms.prefetchPolicy.queuePrefetch=" + queuePrefetch); - connection = factory.createConnection(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - producer = session.createProducer(destination); - final int ttl = 4000; - producer.setTimeToLive(ttl); - - final long sendCount = 10; - final CountDownLatch receivedOneCondition = new CountDownLatch(1); - final CountDownLatch waitCondition = new CountDownLatch(1); - - MessageConsumer consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() { - - @Override - public void onMessage(Message message) { - try { - LOG.info("Got my message: " + message); - receivedOneCondition.countDown(); - waitCondition.await(6, TimeUnit.MINUTES); - LOG.info("acking message: " + message); - message.acknowledge(); - } catch (Exception e) { - e.printStackTrace(); - fail(e.toString()); - } - } - }); - - connection.start(); - - final Thread producingThread = new Thread("Producing Thread") { - @Override - public void run() { - try { - int i = 0; - long tStamp = System.currentTimeMillis(); - while (i++ < sendCount) { - producer.send(session.createTextMessage("test")); - if (i % 100 == 0) { - LOG.info("sent: " + i + " @ " + ((System.currentTimeMillis() - tStamp) / 100) + "m/ms"); - tStamp = System.currentTimeMillis(); - } - } - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - }; - - producingThread.start(); - assertTrue("got one message", receivedOneCondition.await(20, TimeUnit.SECONDS)); - - assertTrue("producer failed to complete within allocated time", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - producingThread.join(1000); - return !producingThread.isAlive(); - } - }, Wait.MAX_WAIT_MILLIS * 10)); - - final DestinationViewMBean view = createView(destination); - - assertTrue("all dispatched up to default prefetch ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return queuePrefetch == view.getDispatchCount(); - } - })); - assertTrue("all non inflight have expired ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize()); - - return view.getExpiredCount() > 0 && (view.getEnqueueCount() - view.getInFlightCount()) == view.getExpiredCount(); - } - })); - - LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize()); - - // let the ack happen - waitCondition.countDown(); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 0 == view.getInFlightCount(); - } - }); - LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize()); - - assertEquals("inflight reduced to duck", 0, view.getInFlightCount()); - assertEquals("size didn't get back to 0 ", 0, view.getQueueSize()); - assertEquals("dequeues didn't match sent/expired ", sendCount, view.getDequeueCount()); - - consumer.close(); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 0 == view.getInFlightCount(); - } - }); - assertEquals("inflight goes to zero on close", 0, view.getInFlightCount()); - - LOG.info("done: " + getName()); - } - - public void testExpiredMessagesWithVerySlowConsumerCanContinue() throws Exception { - createBroker(); - final long queuePrefetch = 600; - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri + "?jms.prefetchPolicy.queuePrefetch=" + queuePrefetch); - connection = factory.createConnection(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - producer = session.createProducer(destination); - final int ttl = 4000; - producer.setTimeToLive(ttl); - - final long sendCount = 1500; - final CountDownLatch receivedOneCondition = new CountDownLatch(1); - final CountDownLatch waitCondition = new CountDownLatch(1); - final AtomicLong received = new AtomicLong(); - MessageConsumer consumer = session.createConsumer(destination); - consumer.setMessageListener(new MessageListener() { - - @Override - public void onMessage(Message message) { - try { - if (LOG.isDebugEnabled()) { - LOG.debug("Got my message: " + message); - } - receivedOneCondition.countDown(); - received.incrementAndGet(); - waitCondition.await(5, TimeUnit.MINUTES); - if (LOG.isDebugEnabled()) { - LOG.debug("acking message: " + message); - } - message.acknowledge(); - } catch (Exception e) { - e.printStackTrace(); - fail(e.toString()); - } - } - }); - - connection.start(); - - final Thread producingThread = new Thread("Producing Thread") { - @Override - public void run() { - try { - int i = 0; - long tStamp = System.currentTimeMillis(); - while (i++ < sendCount) { - producer.send(session.createTextMessage("test")); - if (i % 100 == 0) { - LOG.info("sent: " + i + " @ " + ((System.currentTimeMillis() - tStamp) / 100) + "m/ms"); - tStamp = System.currentTimeMillis(); - } - } - } catch (Throwable ex) { - ex.printStackTrace(); - } - } - }; - - producingThread.start(); - assertTrue("got one message", receivedOneCondition.await(20, TimeUnit.SECONDS)); - - assertTrue("producer failed to complete within allocated time", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - producingThread.join(1000); - return !producingThread.isAlive(); - } - }, Wait.MAX_WAIT_MILLIS * 10)); - - final DestinationViewMBean view = createView(destination); - - assertTrue("Not all dispatched up to default prefetch ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return queuePrefetch == view.getDispatchCount(); - } - })); - - assertTrue("all non inflight have expired ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize()); - - return view.getExpiredCount() > 0 && (view.getEnqueueCount() - view.getInFlightCount()) == view.getExpiredCount(); - } - })); - - LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize()); - - // let the ack happen - waitCondition.countDown(); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 0 == view.getInFlightCount(); - } - }); - LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize()); - - assertEquals("inflight didn't reduce to duck", 0, view.getInFlightCount()); - assertEquals("size doesn't get back to 0 ", 0, view.getQueueSize()); - assertEquals("dequeues don't match sent/expired ", sendCount, view.getDequeueCount()); - - // produce some more - producer.setTimeToLive(0); - long tStamp = System.currentTimeMillis(); - for (int i = 0; i < sendCount; i++) { - producer.send(session.createTextMessage("test-" + i)); - if (i % 100 == 0) { - LOG.info("sent: " + i + " @ " + ((System.currentTimeMillis() - tStamp) / 100) + "m/ms"); - tStamp = System.currentTimeMillis(); - } - } - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return received.get() >= sendCount; - } - }); - - consumer.close(); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 0 == view.getInFlightCount(); - } - }); - assertEquals("inflight did not go to zero on close", 0, view.getInFlightCount()); - - LOG.info("done: " + getName()); - } - - public void testExpireMessagesForDurableSubscriber() throws Exception { - createBroker(); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri); - connection = factory.createConnection(); - connection.setClientID("myConnection"); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - connection.start(); - Topic destination = session.createTopic("test"); - producer = session.createProducer(destination); - final int ttl = 1000; - producer.setTimeToLive(ttl); - - final long sendCount = 10; - - TopicSubscriber sub = session.createDurableSubscriber(destination, "mySub"); - sub.close(); - - for (int i = 0; i < sendCount; i++) { - producer.send(session.createTextMessage("test")); - } - - DestinationViewMBean view = createView((ActiveMQTopic) destination); - - LOG.info("messages sent"); - LOG.info("expired=" + view.getExpiredCount() + " " + view.getEnqueueCount()); - assertEquals(0, view.getExpiredCount()); - assertEquals(10, view.getEnqueueCount()); - - Thread.sleep(5000); - - LOG.info("expired=" + view.getExpiredCount() + " " + view.getEnqueueCount()); - assertEquals(10, view.getExpiredCount()); - assertEquals(10, view.getEnqueueCount()); - - final AtomicLong received = new AtomicLong(); - sub = session.createDurableSubscriber(destination, "mySub"); - sub.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - received.incrementAndGet(); - } - }); - - LOG.info("Waiting for messages to arrive"); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return received.get() >= sendCount; - } - }, 1000); - - LOG.info("received=" + received.get()); - LOG.info("expired=" + view.getExpiredCount() + " " + view.getEnqueueCount()); - - assertEquals(0, received.get()); - assertEquals(10, view.getExpiredCount()); - assertEquals(10, view.getEnqueueCount()); - } - - protected DestinationViewMBean createView(ActiveMQDestination destination) throws Exception { - String domain = "org.apache.activemq"; - ObjectName name; - if (destination.isQueue()) { - name = new ObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Queue,destinationName=test"); - } else { - name = new ObjectName(domain + ":type=Broker,brokerName=localhost,destinationType=Topic,destinationName=test"); - } - - return (DestinationViewMBean) broker.getManagementContext().newProxyInstance(name, DestinationViewMBean.class, true); - } - - @Override - protected void tearDown() throws Exception { - connection.stop(); - broker.stop(); - broker.waitUntilStopped(); - } - - public boolean getOptimizedDispatch() { - return this.optimizedDispatch; - } - - public void setOptimizedDispatch(boolean option) { - this.optimizedDispatch = option; - } - - public PendingQueueMessageStoragePolicy getPendingQueuePolicy() { - return this.pendingQueuePolicy; - } - - public void setPendingQueuePolicy(PendingQueueMessageStoragePolicy policy) { - this.pendingQueuePolicy = policy; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JDBCDurableSubscriptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JDBCDurableSubscriptionTest.java deleted file mode 100644 index 2f4ec86801..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JDBCDurableSubscriptionTest.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.activemq.usecases; - -import java.io.IOException; - -import org.apache.activemq.store.PersistenceAdapter; -import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; -import org.apache.derby.jdbc.EmbeddedDataSource; - -/** - * - */ -public class JDBCDurableSubscriptionTest extends DurableSubscriptionTestSupport { - - @Override - protected PersistenceAdapter createPersistenceAdapter() throws IOException { - JDBCPersistenceAdapter jdbc = new JDBCPersistenceAdapter(); - EmbeddedDataSource dataSource = new EmbeddedDataSource(); - dataSource.setDatabaseName("derbyDb"); - dataSource.setCreateDatabase("create"); - jdbc.setDataSource(dataSource); - jdbc.setCleanupPeriod(1000); // set up small cleanup period - return jdbc; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JMXRemoveQueueThenSendIgnoredTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JMXRemoveQueueThenSendIgnoredTest.java deleted file mode 100644 index 9b0e2fb0d6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JMXRemoveQueueThenSendIgnoredTest.java +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.DeliveryMode; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.QueueConnection; -import javax.jms.QueueSession; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.management.ObjectName; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.jmx.QueueViewMBean; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; - -public class JMXRemoveQueueThenSendIgnoredTest { - - private static final Logger LOG = LoggerFactory.getLogger(JMXRemoveQueueThenSendIgnoredTest.class); - private static final String domain = "org.apache.activemq"; - - private BrokerService brokerService; - private MessageProducer producer; - private QueueSession session; - private QueueConnection connection; - private Queue queue; - private int count = 1; - - @Before - public void setUp() throws Exception { - brokerService = new BrokerService(); - brokerService.setBrokerName("dev"); - brokerService.setPersistent(false); - brokerService.setUseJmx(true); - brokerService.addConnector("tcp://localhost:0"); - brokerService.start(); - - final String brokerUri = brokerService.getTransportConnectors().get(0).getPublishableConnectString(); - - ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(brokerUri); - connection = activeMQConnectionFactory.createQueueConnection(); - session = connection.createQueueSession(true, Session.AUTO_ACKNOWLEDGE/*SESSION_TRANSACTED*/); - queue = session.createQueue("myqueue"); - producer = session.createProducer(queue); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - - connection.start(); - } - - @Test - public void testRemoveQueueAndProduceAfterNewConsumerAdded() throws Exception { - MessageConsumer firstConsumer = registerConsumer(); - produceMessage(); - Message message = firstConsumer.receive(5000); - LOG.info("Received message " + message); - - assertEquals(1, numberOfMessages()); - firstConsumer.close(); - session.commit(); - Thread.sleep(1000); - - removeQueue(); - Thread.sleep(1000); - - MessageConsumer secondConsumer = registerConsumer(); - produceMessage(); - message = secondConsumer.receive(5000); - LOG.debug("Received message " + message); - - assertEquals(1, numberOfMessages()); - secondConsumer.close(); - } - - @Test - public void testRemoveQueueAndProduceBeforeNewConsumerAdded() throws Exception { - MessageConsumer firstConsumer = registerConsumer(); - produceMessage(); - Message message = firstConsumer.receive(5000); - LOG.info("Received message " + message); - - assertEquals(1, numberOfMessages()); - firstConsumer.close(); - session.commit(); - Thread.sleep(1000); - - removeQueue(); - Thread.sleep(1000); - - produceMessage(); - MessageConsumer secondConsumer = registerConsumer(); - message = secondConsumer.receive(5000); - LOG.debug("Received message " + message); - - assertEquals(1, numberOfMessages()); - secondConsumer.close(); - } - - private MessageConsumer registerConsumer() throws JMSException { - MessageConsumer consumer = session.createConsumer(queue); - return consumer; - } - - private int numberOfMessages() throws Exception { - ObjectName queueViewMBeanName = new ObjectName(domain + ":destinationType=Queue,destinationName=myqueue,type=Broker,brokerName=dev"); - QueueViewMBean queue = (QueueViewMBean) brokerService.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); - long size = queue.getQueueSize(); - return (int) size; - } - - private void removeQueue() throws Exception { - LOG.debug("Removing Destination: myqueue"); - brokerService.getAdminView().removeQueue("myqueue"); - } - - private void produceMessage() throws JMSException { - TextMessage textMessage = session.createTextMessage(); - textMessage.setText("Sending message: " + count++); - LOG.debug("Sending message: " + textMessage); - producer.send(textMessage); - session.commit(); - } - - @After - public void tearDown() throws Exception { - connection.close(); - brokerService.stop(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JdbcDurableSubDupTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JdbcDurableSubDupTest.java deleted file mode 100644 index 0a67a15586..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JdbcDurableSubDupTest.java +++ /dev/null @@ -1,290 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.jms.Topic; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Vector; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertTrue; - -public class JdbcDurableSubDupTest { - - private static final Logger LOG = LoggerFactory.getLogger(JdbcDurableSubDupTest.class); - final int prefetchVal = 150; - String urlOptions = "jms.watchTopicAdvisories=false"; - String url = null; - String queueName = "topicTest?consumer.prefetchSize=" + prefetchVal; - String xmlMessage = ""; - - String selector = ""; - String clntVersion = "87"; - String clntId = "timsClntId345" + clntVersion; - String subscriptionName = "subscriptionName-y" + clntVersion; - SimpleDateFormat dtf = new SimpleDateFormat("HH:mm:ss"); - - final int TO_RECEIVE = 5000; - BrokerService broker = null; - Vector exceptions = new Vector<>(); - final int MAX_MESSAGES = 100000; - int[] dupChecker = new int[MAX_MESSAGES]; - - @Before - public void startBroker() throws Exception { - exceptions.clear(); - for (int i = 0; i < MAX_MESSAGES; i++) { - dupChecker[i] = 0; - } - broker = new BrokerService(); - broker.setAdvisorySupport(false); - broker.setPersistenceAdapter(new JDBCPersistenceAdapter()); - PolicyEntry policyEntry = new PolicyEntry(); - policyEntry.setMaxAuditDepth(3000); - policyEntry.setMaxPageSize(150); - policyEntry.setPrioritizedMessages(true); - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(policyEntry); - broker.setDestinationPolicy(policyMap); - - broker.addConnector("tcp://localhost:0"); - broker.setDeleteAllMessagesOnStartup(true); - broker.start(); - broker.waitUntilStarted(); - url = broker.getTransportConnectors().get(0).getConnectUri().toString() + "?" + urlOptions; - } - - @After - public void stopBroker() throws Exception { - if (broker != null) { - broker.stop(); - } - } - - @Test - public void testNoDupsOnSlowConsumerReconnect() throws Exception { - JmsConsumerDup consumer = new JmsConsumerDup(); - consumer.done.set(true); - consumer.run(); - - consumer.done.set(false); - - LOG.info("serial production then consumption"); - JmsProvider provider = new JmsProvider(); - provider.run(); - - consumer.run(); - - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - - for (int i = 0; i < TO_RECEIVE; i++) { - assertTrue("got message " + i, dupChecker[i] == 1); - } - } - - @Test - public void testNoDupsOnSlowConsumerLargePriorityGapReconnect() throws Exception { - JmsConsumerDup consumer = new JmsConsumerDup(); - consumer.done.set(true); - consumer.run(); - - consumer.done.set(false); - JmsProvider provider = new JmsProvider(); - provider.priorityModulator = 2500; - provider.run(); - - consumer.run(); - - assertTrue("no exceptions: " + exceptions, exceptions.isEmpty()); - for (int i = 0; i < TO_RECEIVE; i++) { - assertTrue("got message " + i, dupChecker[i] == 1); - } - - } - - class JmsConsumerDup implements MessageListener { - - long count = 0; - - AtomicBoolean done = new AtomicBoolean(false); - - public void run() { - Connection connection = null; - Session session; - Topic topic; - ActiveMQConnectionFactory factory; - MessageConsumer consumer; - - factory = new ActiveMQConnectionFactory(url); - - try { - connection = factory.createConnection("MyUsername", "MyPassword"); - connection.setClientID(clntId); - connection.start(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - topic = session.createTopic(queueName); - consumer = session.createDurableSubscriber(topic, subscriptionName, selector, false); - consumer.setMessageListener(this); - LOG.info("Waiting for messages..."); - - while (!done.get()) { - TimeUnit.SECONDS.sleep(5); - if (count == TO_RECEIVE || !exceptions.isEmpty()) { - done.set(true); - } - } - } catch (Exception e) { - LOG.error("caught", e); - exceptions.add(e); - throw new RuntimeException(e); - } finally { - if (connection != null) { - try { - LOG.info("consumer done (" + exceptions.isEmpty() + "), closing connection"); - connection.close(); - } catch (JMSException e) { - e.printStackTrace(); - } - } - } - } - - @Override - public void onMessage(Message message) { - ++count; - - try { - Thread.sleep(0L); - } catch (InterruptedException e) { - } - - try { - TextMessage m = (TextMessage) message; - - if (count % 100 == 0) { - LOG.info("Rcvd Msg #-" + count + " " + m.getText() + " Sent->" + dtf.format(new Date(m.getJMSTimestamp())) + " Recv->" + dtf.format(new Date()) + " Expr->" + dtf.format(new Date(m.getJMSExpiration())) + ", mid: " + m.getJMSMessageID()); - } - int i = m.getIntProperty("SeqNo"); - - //check for duplicate messages - if (i < MAX_MESSAGES) { - if (dupChecker[i] == 1) { - LOG.error("Duplicate message received at count: " + count + ", id: " + m.getJMSMessageID()); - exceptions.add(new RuntimeException("Got Duplicate at: " + m.getJMSMessageID())); - - } else { - dupChecker[i] = 1; - } - } - } catch (JMSException e) { - LOG.error("caught ", e); - exceptions.add(e); - } - } - } - - class JmsProvider implements Runnable { - - int priorityModulator = 10; - - @Override - public void run() { - - Connection connection; - Session session; - Topic topic; - - ActiveMQConnectionFactory factory; - MessageProducer messageProducer; - long timeToLive = 0L; - - TextMessage message = null; - - factory = new ActiveMQConnectionFactory(url); - - try { - connection = factory.createConnection("MyUserName", "MyPassword"); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - topic = session.createTopic(queueName); - messageProducer = session.createProducer(topic); - messageProducer.setPriority(3); - messageProducer.setTimeToLive(timeToLive); - messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT); - - int msgSeqNo = 0; - int NUM_MSGS = 1000; - int NUM_GROUPS = TO_RECEIVE / NUM_MSGS; - for (int n = 0; n < NUM_GROUPS; n++) { - - message = session.createTextMessage(); - - for (int i = 0; i < NUM_MSGS; i++) { - int priority = 0; - if (priorityModulator <= 10) { - priority = msgSeqNo % priorityModulator; - } else { - priority = (msgSeqNo >= priorityModulator) ? 9 : 0; - } - message.setText(xmlMessage + msgSeqNo + "-" + priority); - message.setJMSPriority(priority); - message.setIntProperty("SeqNo", msgSeqNo); - if (i > 0 && i % 100 == 0) { - LOG.info("Sending message: " + message.getText()); - } - messageProducer.send(message, DeliveryMode.PERSISTENT, message.getJMSPriority(), timeToLive); - msgSeqNo++; - } - try { - Thread.sleep(1000L); - } catch (InterruptedException e) { - e.printStackTrace(); - exceptions.add(e); - } - } - - } catch (JMSException e) { - LOG.error("caught ", e); - e.printStackTrace(); - exceptions.add(e); - - } - } - - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JournalDurableSubscriptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JournalDurableSubscriptionTest.java deleted file mode 100644 index b6bcd5a8b4..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/JournalDurableSubscriptionTest.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.activemq.usecases; - -import java.io.File; -import java.io.IOException; - -import org.apache.activemq.store.PersistenceAdapter; -import org.apache.activemq.store.journal.JournalPersistenceAdapterFactory; - -/** - * - */ -public class JournalDurableSubscriptionTest extends DurableSubscriptionTestSupport { - - @Override - protected PersistenceAdapter createPersistenceAdapter() throws IOException { - File dataDir = new File("target/test-data/durableJournal"); - JournalPersistenceAdapterFactory factory = new JournalPersistenceAdapterFactory(); - factory.setDataDirectoryFile(dataDir); - factory.setUseJournal(true); - factory.setJournalLogFileSize(1024 * 64); - return factory.createPersistenceAdapter(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/KahaDBDurableSubscriptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/KahaDBDurableSubscriptionTest.java deleted file mode 100644 index 2fc71c04f3..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/KahaDBDurableSubscriptionTest.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.activemq.usecases; - -import java.io.IOException; - -import org.apache.activemq.store.PersistenceAdapter; - -public class KahaDBDurableSubscriptionTest extends DurableSubscriptionTestSupport { - - @Override - protected PersistenceAdapter createPersistenceAdapter() throws IOException { - return null; // use default - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/LargeQueueSparseDeleteTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/LargeQueueSparseDeleteTest.java deleted file mode 100644 index 7fe27884f6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/LargeQueueSparseDeleteTest.java +++ /dev/null @@ -1,177 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageProducer; -import javax.jms.Session; - -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.apache.activemq.broker.ConnectionContext; -import org.apache.activemq.broker.region.Queue; -import org.apache.activemq.filter.NonCachedMessageEvaluationContext; -import org.junit.Assert; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This unit test creates a fixed size queue and moves the last message in the - * queue to another queue. The test is used to very the performance of - * {@link org.apache.activemq.broker.region.Queue#moveMatchingMessagesTo(org.apache.activemq.broker.ConnectionContext, String, org.apache.activemq.command.ActiveMQDestination)}. - */ -public class LargeQueueSparseDeleteTest extends EmbeddedBrokerTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(LargeQueueSparseDeleteTest.class); - - /** - * {@inheritDoc} - */ - @Override - protected void setUp() throws Exception { - super.useTopic = false; - super.setUp(); - } - - /** - * The test queue is filled with QUEUE_SIZE test messages, each with a - * numeric id property beginning at 0. Once the queue is filled, the last - * message (id = QUEUE_SIZE-1) is moved to another queue. The test succeeds - * if the move completes within TEST_TIMEOUT milliseconds. - * - * @throws Exception - */ - public void testMoveMessages() throws Exception { - final int QUEUE_SIZE = 30000; - final String MOVE_TO_DESTINATION_NAME = getDestinationString() + ".dest"; - final long TEST_TIMEOUT = 20000; - - // Populate a test queue with uniquely-identifiable messages. - Connection conn = createConnection(); - try { - conn.start(); - Session session = conn.createSession(true, Session.SESSION_TRANSACTED); - MessageProducer producer = session.createProducer(destination); - for (int i = 0; i < QUEUE_SIZE; i++) { - Message message = session.createMessage(); - message.setIntProperty("id", i); - producer.send(message); - } - session.commit(); - } finally { - conn.close(); - } - - // Access the implementation of the test queue and move the last message - // to another queue. Verify that the move occurred within the limits of - // the test. - Queue queue = (Queue) broker.getRegionBroker().getDestinationMap().get(destination); - - ConnectionContext context = new ConnectionContext(new NonCachedMessageEvaluationContext()); - context.setBroker(broker.getBroker()); - context.getMessageEvaluationContext().setDestination(destination); - - long startTimeMillis = System.currentTimeMillis(); - Assert.assertEquals(1, queue.moveMatchingMessagesTo(context, "id=" + (QUEUE_SIZE - 1), createDestination(MOVE_TO_DESTINATION_NAME))); - - long durationMillis = System.currentTimeMillis() - startTimeMillis; - - LOG.info("It took " + durationMillis + "ms to move the last message from a queue a " + QUEUE_SIZE + " messages."); - - Assert.assertTrue("Moving the message took too long: " + durationMillis + "ms", durationMillis < TEST_TIMEOUT); - } - - public void testCopyMessages() throws Exception { - final int QUEUE_SIZE = 30000; - final String MOVE_TO_DESTINATION_NAME = getDestinationString() + ".dest"; - final long TEST_TIMEOUT = 10000; - - // Populate a test queue with uniquely-identifiable messages. - Connection conn = createConnection(); - try { - conn.start(); - Session session = conn.createSession(true, Session.SESSION_TRANSACTED); - MessageProducer producer = session.createProducer(destination); - for (int i = 0; i < QUEUE_SIZE; i++) { - Message message = session.createMessage(); - message.setIntProperty("id", i); - producer.send(message); - } - session.commit(); - } finally { - conn.close(); - } - - // Access the implementation of the test queue and move the last message - // to another queue. Verify that the move occurred within the limits of - // the test. - Queue queue = (Queue) broker.getRegionBroker().getDestinationMap().get(destination); - - ConnectionContext context = new ConnectionContext(new NonCachedMessageEvaluationContext()); - context.setBroker(broker.getBroker()); - context.getMessageEvaluationContext().setDestination(destination); - - long startTimeMillis = System.currentTimeMillis(); - Assert.assertEquals(1, queue.copyMatchingMessagesTo(context, "id=" + (QUEUE_SIZE - 1), createDestination(MOVE_TO_DESTINATION_NAME))); - - long durationMillis = System.currentTimeMillis() - startTimeMillis; - - LOG.info("It took " + durationMillis + "ms to copy the last message from a queue a " + QUEUE_SIZE + " messages."); - - Assert.assertTrue("Copying the message took too long: " + durationMillis + "ms", durationMillis < TEST_TIMEOUT); - } - - public void testRemoveMessages() throws Exception { - final int QUEUE_SIZE = 30000; - final long TEST_TIMEOUT = 20000; - - // Populate a test queue with uniquely-identifiable messages. - Connection conn = createConnection(); - try { - conn.start(); - Session session = conn.createSession(true, Session.SESSION_TRANSACTED); - MessageProducer producer = session.createProducer(destination); - for (int i = 0; i < QUEUE_SIZE; i++) { - Message message = session.createMessage(); - message.setIntProperty("id", i); - producer.send(message); - } - session.commit(); - } finally { - conn.close(); - } - - // Access the implementation of the test queue and move the last message - // to another queue. Verify that the move occurred within the limits of - // the test. - Queue queue = (Queue) broker.getRegionBroker().getDestinationMap().get(destination); - - ConnectionContext context = new ConnectionContext(new NonCachedMessageEvaluationContext()); - context.setBroker(broker.getBroker()); - context.getMessageEvaluationContext().setDestination(destination); - - long startTimeMillis = System.currentTimeMillis(); - Assert.assertEquals(1, queue.removeMatchingMessages("id=" + (QUEUE_SIZE - 1))); - - long durationMillis = System.currentTimeMillis() - startTimeMillis; - - LOG.info("It took " + durationMillis + "ms to remove the last message from a queue a " + QUEUE_SIZE + " messages."); - - Assert.assertTrue("Removing the message took too long: " + durationMillis + "ms", durationMillis < TEST_TIMEOUT); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/LevelDBDurableSubscriptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/LevelDBDurableSubscriptionTest.java deleted file mode 100644 index 051eed3ca6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/LevelDBDurableSubscriptionTest.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.activemq.usecases; - -import java.io.File; -import java.io.IOException; - -import org.apache.activemq.leveldb.LevelDBStore; -import org.apache.activemq.store.PersistenceAdapter; - -/** - * - */ -public class LevelDBDurableSubscriptionTest extends DurableSubscriptionTestSupport { - - @Override - protected PersistenceAdapter createPersistenceAdapter() throws IOException { - File dataDir = new File("target/test-data/durableLevelDB"); - LevelDBStore adaptor = new LevelDBStore(); - adaptor.setDirectory(dataDir); - return adaptor; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ManagedDurableSubscriptionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ManagedDurableSubscriptionTest.java deleted file mode 100644 index 51e7281827..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ManagedDurableSubscriptionTest.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.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Session; -import javax.management.ObjectName; -import java.io.File; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.leveldb.LevelDBStore; - -public class ManagedDurableSubscriptionTest extends org.apache.activemq.TestSupport { - - BrokerService broker = null; - Connection connection = null; - ActiveMQTopic topic; - - public void testJMXSubscriptions() throws Exception { - // create durable subscription - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId"); - session.close(); - - // restart the broker - stopBroker(); - startBroker(); - - ObjectName inactiveSubscriptionObjectName = broker.getAdminView().getInactiveDurableTopicSubscribers()[0]; - - Object inactive = broker.getManagementContext().getAttribute(inactiveSubscriptionObjectName, "Active"); - assertTrue("Subscription is active.", Boolean.FALSE.equals(inactive)); - - // activate - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createDurableSubscriber(topic, "SubsId"); - - ObjectName activeSubscriptionObjectName = broker.getAdminView().getDurableTopicSubscribers()[0]; - - Object active = broker.getManagementContext().getAttribute(activeSubscriptionObjectName, "Active"); - assertTrue("Subscription is INactive.", Boolean.TRUE.equals(active)); - - // deactivate - connection.close(); - connection = null; - - inactive = broker.getManagementContext().getAttribute(inactiveSubscriptionObjectName, "Active"); - assertTrue("Subscription is active.", Boolean.FALSE.equals(inactive)); - - } - - private void startBroker() throws Exception { - broker = BrokerFactory.createBroker("broker:(vm://localhost)"); - broker.setKeepDurableSubsActive(false); - broker.setPersistent(true); - LevelDBStore persistenceAdapter = new LevelDBStore(); - persistenceAdapter.setDirectory(new File("activemq-data/" + getName())); - broker.setPersistenceAdapter(persistenceAdapter); - broker.setUseJmx(true); - broker.getManagementContext().setCreateConnector(false); - broker.setBrokerName(getName()); - broker.start(); - - connection = createConnection(); - } - - private void stopBroker() throws Exception { - if (connection != null) - connection.close(); - connection = null; - if (broker != null) - broker.stop(); - broker = null; - } - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://" + getName() + "?waitForStart=5000&create=false"); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - - topic = (ActiveMQTopic) createDestination(); - startBroker(); - } - - @Override - protected void tearDown() throws Exception { - stopBroker(); - super.tearDown(); - } - - @Override - protected Connection createConnection() throws Exception { - Connection rc = super.createConnection(); - rc.setClientID(getName()); - rc.start(); - return rc; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MemoryLimitTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MemoryLimitTest.java deleted file mode 100644 index b545056851..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MemoryLimitTest.java +++ /dev/null @@ -1,204 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.BytesMessage; -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.Queue; -import javax.jms.Session; -import java.util.Arrays; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.TestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.Destination; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.util.ConsumerThread; -import org.apache.activemq.util.ProducerThread; -import org.apache.activemq.util.Wait; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@RunWith(value = Parameterized.class) -public class MemoryLimitTest extends TestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(MemoryLimitTest.class); - final byte[] payload = new byte[10 * 1024]; //10KB - protected BrokerService broker; - - @Parameterized.Parameter - public TestSupport.PersistenceAdapterChoice persistenceAdapterChoice; - - @Parameterized.Parameters(name = "store={0}") - public static Iterable getTestParameters() { - return Arrays.asList(new Object[][]{{TestSupport.PersistenceAdapterChoice.KahaDB}, {PersistenceAdapterChoice.LevelDB}, {PersistenceAdapterChoice.JDBC}}); - } - - protected BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.getSystemUsage().getMemoryUsage().setLimit(1 * 1024 * 1024); //1MB - broker.deleteAllMessages(); - - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policyEntry = new PolicyEntry(); - policyEntry.setProducerFlowControl(false); - policyMap.put(new ActiveMQQueue(">"), policyEntry); - broker.setDestinationPolicy(policyMap); - - LOG.info("Starting broker with persistenceAdapterChoice " + persistenceAdapterChoice.toString()); - setPersistenceAdapter(broker, persistenceAdapterChoice); - broker.getPersistenceAdapter().deleteAllMessages(); - - return broker; - } - - @Override - @Before - public void setUp() throws Exception { - if (broker == null) { - broker = createBroker(); - } - broker.start(); - broker.waitUntilStarted(); - } - - @Override - @After - public void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - broker.waitUntilStopped(); - } - } - - @Test(timeout = 120000) - public void testCursorBatch() throws Exception { - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?jms.prefetchPolicy.all=10"); - factory.setOptimizeAcknowledge(true); - Connection conn = factory.createConnection(); - conn.start(); - Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); - Queue queue = sess.createQueue("STORE"); - final ProducerThread producer = new ProducerThread(sess, queue) { - @Override - protected Message createMessage(int i) throws Exception { - BytesMessage bytesMessage = sess.createBytesMessage(); - bytesMessage.writeBytes(payload); - return bytesMessage; - } - }; - producer.setMessageCount(2000); - producer.start(); - producer.join(); - - Thread.sleep(1000); - - // assert we didn't break high watermark (70%) usage - final Destination dest = broker.getDestination((ActiveMQQueue) queue); - LOG.info("Destination usage: " + dest.getMemoryUsage()); - int percentUsage = dest.getMemoryUsage().getPercentUsage(); - assertTrue("Should be less than 70% of limit but was: " + percentUsage, percentUsage <= 71); - LOG.info("Broker usage: " + broker.getSystemUsage().getMemoryUsage()); - assertTrue(broker.getSystemUsage().getMemoryUsage().getPercentUsage() <= 71); - - // consume one message - MessageConsumer consumer = sess.createConsumer(queue); - Message msg = consumer.receive(5000); - msg.acknowledge(); - - // this should free some space and allow us to get new batch of messages in the memory - // exceeding the limit - assertTrue("Limit is exceeded", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Destination usage: " + dest.getMemoryUsage()); - return dest.getMemoryUsage().getPercentUsage() >= 200; - } - })); - - LOG.info("Broker usage: " + broker.getSystemUsage().getMemoryUsage()); - assertTrue(broker.getSystemUsage().getMemoryUsage().getPercentUsage() >= 200); - - // let's make sure we can consume all messages - for (int i = 1; i < 2000; i++) { - msg = consumer.receive(5000); - if (msg == null) { - dumpAllThreads("NoMessage"); - } - assertNotNull("Didn't receive message " + i, msg); - msg.acknowledge(); - } - } - - /** - * Handy test for manually checking what's going on - */ - @Ignore - @Test(timeout = 120000) - public void testLimit() throws Exception { - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?jms.prefetchPolicy.all=10"); - factory.setOptimizeAcknowledge(true); - Connection conn = factory.createConnection(); - conn.start(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - final ProducerThread producer = new ProducerThread(sess, sess.createQueue("STORE.1")) { - @Override - protected Message createMessage(int i) throws Exception { - return sess.createTextMessage(Arrays.toString(payload) + "::" + i); - } - }; - producer.setMessageCount(1000); - - final ProducerThread producer2 = new ProducerThread(sess, sess.createQueue("STORE.2")) { - @Override - protected Message createMessage(int i) throws Exception { - return sess.createTextMessage(Arrays.toString(payload) + "::" + i); - } - }; - producer2.setMessageCount(1000); - - ConsumerThread consumer = new ConsumerThread(sess, sess.createQueue("STORE.1")); - consumer.setBreakOnNull(false); - consumer.setMessageCount(1000); - - producer.start(); - producer.join(); - - producer2.start(); - - Thread.sleep(300); - - consumer.start(); - - consumer.join(); - producer2.join(); - - assertEquals("consumer got all produced messages", producer.getMessageCount(), consumer.getReceived()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupCloseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupCloseTest.java deleted file mode 100644 index 0795466b2c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupCloseTest.java +++ /dev/null @@ -1,254 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.CountDownLatch; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/* - * Test plan: - * Producer: publish messages into a queue, with 10 message groups, closing the group with seq=-1 on message 5 and message 10 - * Consumers: 2 consumers created after all messages are sent - * - * Expected: for each group, messages 1-5 are handled by one consumer and messages 6-10 are handled by the other consumer. Messages - * 1 and 6 have the JMSXGroupFirstForConsumer property set to true. - */ -public class MessageGroupCloseTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(MessageGroupNewConsumerTest.class); - private Connection connection; - // Released after all messages are created - private CountDownLatch latchMessagesCreated = new CountDownLatch(1); - - private int messagesSent, messagesRecvd1, messagesRecvd2, messageGroupCount, errorCountFirstForConsumer, errorCountWrongConsumerClose, errorCountDuplicateClose; - // groupID, count - private HashMap messageGroups1 = new HashMap<>(); - private HashMap messageGroups2 = new HashMap<>(); - private HashSet closedGroups1 = new HashSet<>(); - private HashSet closedGroups2 = new HashSet<>(); - // with the prefetch too high, this bug is not realized - private static final String connStr = "vm://localhost?broker.persistent=false&broker.useJmx=false&jms.prefetchPolicy.all=1"; - - public void testNewConsumer() throws JMSException, InterruptedException { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connStr); - connection = factory.createConnection(); - connection.start(); - final String queueName = this.getClass().getSimpleName(); - final Thread producerThread = new Thread() { - @Override - public void run() { - try { - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Queue queue = session.createQueue(queueName); - MessageProducer prod = session.createProducer(queue); - for (int i = 0; i < 10; i++) { - for (int j = 0; j < 10; j++) { - int seq = j + 1; - if ((j + 1) % 5 == 0) { - seq = -1; - } - Message message = generateMessage(session, Integer.toString(i), seq); - prod.send(message); - session.commit(); - messagesSent++; - LOG.info("Sent message: group=" + i + ", seq=" + seq); - //Thread.sleep(20); - } - if (i % 100 == 0) { - LOG.info("Sent messages: group=" + i); - } - setMessageGroupCount(getMessageGroupCount() + 1); - } - LOG.info(messagesSent + " messages sent"); - latchMessagesCreated.countDown(); - prod.close(); - session.close(); - } catch (Exception e) { - LOG.error("Producer failed", e); - } - } - }; - final Thread consumerThread1 = new Thread() { - @Override - public void run() { - try { - latchMessagesCreated.await(); - LOG.info("starting consumer1"); - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Queue queue = session.createQueue(queueName); - MessageConsumer con1 = session.createConsumer(queue); - while (true) { - Message message = con1.receive(5000); - if (message == null) - break; - LOG.info("Con1: got message " + formatMessage(message)); - checkMessage(message, "Con1", messageGroups1, closedGroups1); - session.commit(); - messagesRecvd1++; - if (messagesRecvd1 % 100 == 0) { - LOG.info("Con1: got messages count=" + messagesRecvd1); - } - //Thread.sleep(50); - } - LOG.info("Con1: total messages=" + messagesRecvd1); - LOG.info("Con1: total message groups=" + messageGroups1.size()); - con1.close(); - session.close(); - } catch (Exception e) { - LOG.error("Consumer 1 failed", e); - } - } - }; - final Thread consumerThread2 = new Thread() { - @Override - public void run() { - try { - latchMessagesCreated.await(); - LOG.info("starting consumer2"); - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Queue queue = session.createQueue(queueName); - MessageConsumer con2 = session.createConsumer(queue); - while (true) { - Message message = con2.receive(5000); - if (message == null) { - break; - } - LOG.info("Con2: got message " + formatMessage(message)); - checkMessage(message, "Con2", messageGroups2, closedGroups2); - session.commit(); - messagesRecvd2++; - if (messagesRecvd2 % 100 == 0) { - LOG.info("Con2: got messages count=" + messagesRecvd2); - } - //Thread.sleep(50); - } - con2.close(); - session.close(); - LOG.info("Con2: total messages=" + messagesRecvd2); - LOG.info("Con2: total message groups=" + messageGroups2.size()); - } catch (Exception e) { - LOG.error("Consumer 2 failed", e); - } - } - }; - consumerThread2.start(); - consumerThread1.start(); - producerThread.start(); - // wait for threads to finish - producerThread.join(); - consumerThread1.join(); - consumerThread2.join(); - connection.close(); - // check results - - assertEquals("consumers should get all the messages", messagesSent, messagesRecvd1 + messagesRecvd2); - assertEquals("not all message groups closed for consumer 1", messageGroups1.size(), closedGroups1.size()); - assertEquals("not all message groups closed for consumer 2", messageGroups2.size(), closedGroups2.size()); - assertTrue("producer failed to send any messages", messagesSent > 0); - assertEquals("JMSXGroupFirstForConsumer not set", 0, errorCountFirstForConsumer); - assertEquals("wrong consumer got close message", 0, errorCountWrongConsumerClose); - assertEquals("consumer got duplicate close message", 0, errorCountDuplicateClose); - } - - public Message generateMessage(Session session, String groupId, int seq) throws JMSException { - TextMessage m = session.createTextMessage(); - m.setJMSType("TEST_MESSAGE"); - m.setStringProperty("JMSXGroupID", groupId); - m.setIntProperty("JMSXGroupSeq", seq); - m.setText(""); - return m; - } - - public String formatMessage(Message m) { - try { - return "group=" + m.getStringProperty("JMSXGroupID") + ", seq=" + m.getIntProperty("JMSXGroupSeq"); - } catch (Exception e) { - return e.getClass().getSimpleName() + ": " + e.getMessage(); - } - } - - public void checkMessage(Message m, - String consumerId, - Map messageGroups, - Set closedGroups) throws JMSException { - String groupId = m.getStringProperty("JMSXGroupID"); - int seq = m.getIntProperty("JMSXGroupSeq"); - Integer count = messageGroups.get(groupId); - if (count == null) { - // first time seeing this group - if (!m.propertyExists("JMSXGroupFirstForConsumer") || !m.getBooleanProperty("JMSXGroupFirstForConsumer")) { - LOG.info(consumerId + ": JMSXGroupFirstForConsumer not set for group=" + groupId + ", seq=" + seq); - errorCountFirstForConsumer++; - } - if (seq == -1) { - closedGroups.add(groupId); - LOG.info(consumerId + ": wrong consumer got close message for group=" + groupId); - errorCountWrongConsumerClose++; - } - messageGroups.put(groupId, 1); - } else { - // existing group - if (closedGroups.contains(groupId)) { - // group reassigned to same consumer - closedGroups.remove(groupId); - if (!m.propertyExists("JMSXGroupFirstForConsumer") || !m.getBooleanProperty("JMSXGroupFirstForConsumer")) { - LOG.info(consumerId + ": JMSXGroupFirstForConsumer not set for group=" + groupId + ", seq=" + seq); - errorCountFirstForConsumer++; - } - if (seq == -1) { - LOG.info(consumerId + ": consumer got duplicate close message for group=" + groupId); - errorCountDuplicateClose++; - } - } - if (seq == -1) { - closedGroups.add(groupId); - } - messageGroups.put(groupId, count + 1); - } - } - - /** - * @return the messageGroupCount - */ - public int getMessageGroupCount() { - return messageGroupCount; - } - - /** - * @param messageGroupCount the messageGroupCount to set - */ - public void setMessageGroupCount(int messageGroupCount) { - this.messageGroupCount = messageGroupCount; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupDelayedTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupDelayedTest.java deleted file mode 100644 index 670d20939d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupDelayedTest.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.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.CountDownLatch; - -import junit.framework.Test; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.JmsTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQQueue; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MessageGroupDelayedTest extends JmsTestSupport { - - public static final Logger log = LoggerFactory.getLogger(MessageGroupDelayedTest.class); - protected Connection connection; - protected Session session; - protected MessageProducer producer; - protected Destination destination; - - public int consumersBeforeDispatchStarts; - public int timeBeforeDispatchStarts; - - BrokerService broker; - protected TransportConnector connector; - - protected HashMap messageCount = new HashMap<>(); - protected HashMap> messageGroups = new HashMap<>(); - - public static Test suite() { - return suite(MessageGroupDelayedTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - @Override - public void setUp() throws Exception { - broker = createBroker(); - broker.start(); - ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory(connector.getConnectUri() + "?jms.prefetchPolicy.all=1"); - connection = connFactory.createConnection(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - destination = new ActiveMQQueue("test-queue2"); - producer = session.createProducer(destination); - connection.start(); - } - - @Override - protected BrokerService createBroker() throws Exception { - BrokerService service = new BrokerService(); - service.setPersistent(false); - service.setUseJmx(false); - - // Setup a destination policy where it takes only 1 message at a time. - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policy = new PolicyEntry(); - log.info("testing with consumersBeforeDispatchStarts=" + consumersBeforeDispatchStarts + " and timeBeforeDispatchStarts=" + timeBeforeDispatchStarts); - policy.setConsumersBeforeDispatchStarts(consumersBeforeDispatchStarts); - policy.setTimeBeforeDispatchStarts(timeBeforeDispatchStarts); - policyMap.setDefaultEntry(policy); - service.setDestinationPolicy(policyMap); - - connector = service.addConnector("tcp://localhost:0"); - return service; - } - - @Override - public void tearDown() throws Exception { - producer.close(); - session.close(); - connection.close(); - broker.stop(); - } - - public void initCombosForTestDelayedDirectConnectionListener() { - addCombinationValues("consumersBeforeDispatchStarts", new Object[]{0, 3, 5}); - addCombinationValues("timeBeforeDispatchStarts", new Object[]{0, 100}); - } - - public void testDelayedDirectConnectionListener() throws Exception { - - for (int i = 0; i < 10; i++) { - Message msga = session.createTextMessage("hello a"); - msga.setStringProperty("JMSXGroupID", "A"); - producer.send(msga); - Message msgb = session.createTextMessage("hello b"); - msgb.setStringProperty("JMSXGroupID", "B"); - producer.send(msgb); - Message msgc = session.createTextMessage("hello c"); - msgc.setStringProperty("JMSXGroupID", "C"); - producer.send(msgc); - } - log.info("30 messages sent to group A/B/C"); - - int[] counters = {10, 10, 10}; - - CountDownLatch startSignal = new CountDownLatch(1); - CountDownLatch doneSignal = new CountDownLatch(1); - - messageCount.put("worker1", 0); - messageGroups.put("worker1", new HashSet()); - Worker worker1 = new Worker(connection, destination, "worker1", startSignal, doneSignal, counters, messageCount, messageGroups); - messageCount.put("worker2", 0); - messageGroups.put("worker2", new HashSet()); - Worker worker2 = new Worker(connection, destination, "worker2", startSignal, doneSignal, counters, messageCount, messageGroups); - messageCount.put("worker3", 0); - messageGroups.put("worker3", new HashSet()); - Worker worker3 = new Worker(connection, destination, "worker3", startSignal, doneSignal, counters, messageCount, messageGroups); - - new Thread(worker1).start(); - new Thread(worker2).start(); - new Thread(worker3).start(); - - startSignal.countDown(); - doneSignal.await(); - - // check results - if (consumersBeforeDispatchStarts == 0 && timeBeforeDispatchStarts == 0) { - log.info("Ignoring results because both parameters are 0"); - return; - } - - for (String worker : messageCount.keySet()) { - log.info("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker)); - assertEquals("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker), 10, messageCount.get(worker).intValue()); - assertEquals("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker), 1, messageGroups.get(worker).size()); - } - - } - - private static final class Worker implements Runnable { - - private Connection connection = null; - private Destination queueName = null; - private String workerName = null; - private CountDownLatch startSignal = null; - private CountDownLatch doneSignal = null; - private int[] counters = null; - private final HashMap messageCount; - private final HashMap> messageGroups; - - private Worker(Connection connection, - Destination queueName, - String workerName, - CountDownLatch startSignal, - CountDownLatch doneSignal, - int[] counters, - HashMap messageCount, - HashMap> messageGroups) { - this.connection = connection; - this.queueName = queueName; - this.workerName = workerName; - this.startSignal = startSignal; - this.doneSignal = doneSignal; - this.counters = counters; - this.messageCount = messageCount; - this.messageGroups = messageGroups; - } - - private void update(String group) { - int msgCount = messageCount.get(workerName); - messageCount.put(workerName, msgCount + 1); - Set groups = messageGroups.get(workerName); - groups.add(group); - messageGroups.put(workerName, groups); - } - - @Override - public void run() { - - try { - log.info(workerName); - startSignal.await(); - Session sess = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = sess.createConsumer(queueName); - - while (true) { - if (counters[0] == 0 && counters[1] == 0 && counters[2] == 0) { - doneSignal.countDown(); - log.info(workerName + " done..."); - break; - } - - Message msg = consumer.receive(500); - if (msg == null) - continue; - - String group = msg.getStringProperty("JMSXGroupID"); - msg.getBooleanProperty("JMSXGroupFirstForConsumer"); - - if ("A".equals(group)) { - --counters[0]; - update(group); - Thread.sleep(500); - } else if ("B".equals(group)) { - --counters[1]; - update(group); - Thread.sleep(100); - } else if ("C".equals(group)) { - --counters[2]; - update(group); - Thread.sleep(10); - } else { - log.warn("unknown group"); - } - if (counters[0] != 0 || counters[1] != 0 || counters[2] != 0) { - msg.acknowledge(); - } - } - consumer.close(); - sess.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupLateArrivalsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupLateArrivalsTest.java deleted file mode 100644 index f99d6de939..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupLateArrivalsTest.java +++ /dev/null @@ -1,304 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.CountDownLatch; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQQueue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.BlockJUnit4ClassRunner; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; - -@RunWith(BlockJUnit4ClassRunner.class) -public class MessageGroupLateArrivalsTest { - - public static final Logger log = LoggerFactory.getLogger(MessageGroupLateArrivalsTest.class); - protected Connection connection; - protected Session session; - protected MessageProducer producer; - protected Destination destination; - - BrokerService broker; - protected TransportConnector connector; - - protected HashMap messageCount = new HashMap<>(); - protected HashMap> messageGroups = new HashMap<>(); - - @Before - public void setUp() throws Exception { - broker = createBroker(); - broker.start(); - ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory(connector.getConnectUri() + "?jms.prefetchPolicy.all=1000"); - connection = connFactory.createConnection(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - destination = new ActiveMQQueue("test-queue2"); - producer = session.createProducer(destination); - connection.start(); - } - - protected BrokerService createBroker() throws Exception { - BrokerService service = new BrokerService(); - service.setPersistent(false); - service.setUseJmx(false); - - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policy = new PolicyEntry(); - policy.setUseConsumerPriority(true); - policyMap.setDefaultEntry(policy); - service.setDestinationPolicy(policyMap); - - connector = service.addConnector("tcp://localhost:0"); - return service; - } - - @After - public void tearDown() throws Exception { - producer.close(); - session.close(); - connection.close(); - broker.stop(); - } - - @Test(timeout = 30 * 1000) - public void testConsumersLateToThePartyGetSomeNewGroups() throws Exception { - - final int perBatch = 3; - int[] counters = {perBatch, perBatch, perBatch}; - - CountDownLatch startSignal = new CountDownLatch(0); - CountDownLatch doneSignal = new CountDownLatch(3); - CountDownLatch worker1Started = new CountDownLatch(1); - CountDownLatch worker2Started = new CountDownLatch(1); - CountDownLatch worker3Started = new CountDownLatch(1); - - messageCount.put("worker1", 0); - messageGroups.put("worker1", new HashSet()); - Worker worker1 = new Worker(connection, destination, "worker1", startSignal, doneSignal, counters, messageCount, messageGroups, worker1Started); - messageCount.put("worker2", 0); - messageGroups.put("worker2", new HashSet()); - Worker worker2 = new Worker(connection, destination, "worker2", startSignal, doneSignal, counters, messageCount, messageGroups, worker2Started); - messageCount.put("worker3", 0); - messageGroups.put("worker3", new HashSet()); - Worker worker3 = new Worker(connection, destination, "worker3", startSignal, doneSignal, counters, messageCount, messageGroups, worker3Started); - - new Thread(worker1).start(); - new Thread(worker2).start(); - worker1Started.await(); - worker2Started.await(); - - for (int i = 0; i < perBatch; i++) { - Message msga = session.createTextMessage("hello a"); - msga.setStringProperty("JMSXGroupID", "A"); - producer.send(msga); - - Message msgb = session.createTextMessage("hello b"); - msgb.setStringProperty("JMSXGroupID", "B"); - producer.send(msgb); - } - - // ensure this chap, late to the party gets a new group - new Thread(worker3).start(); - - // wait for presence before new group - worker3Started.await(); - - for (int i = 0; i < perBatch; i++) { - Message msgc = session.createTextMessage("hello c"); - msgc.setStringProperty("JMSXGroupID", "C"); - producer.send(msgc); - } - - doneSignal.await(); - - List workers = new ArrayList<>(messageCount.keySet()); - Collections.sort(workers); - for (String worker : workers) { - log.info("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker)); - } - - for (String worker : workers) { - assertEquals("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker), perBatch, messageCount.get(worker).intValue()); - assertEquals("worker " + worker + " received " + messageCount.get(worker) + " messages from groups " + messageGroups.get(worker), 1, messageGroups.get(worker).size()); - } - } - - @Test(timeout = 30 * 1000) - public void testConsumerLateToBigPartyGetsNewGroup() throws Exception { - - final int perBatch = 2; - int[] counters = {perBatch, perBatch, perBatch}; - - CountDownLatch startSignal = new CountDownLatch(0); - CountDownLatch doneSignal = new CountDownLatch(2); - CountDownLatch worker1Started = new CountDownLatch(1); - CountDownLatch worker2Started = new CountDownLatch(1); - - messageCount.put("worker1", 0); - messageGroups.put("worker1", new HashSet()); - Worker worker1 = new Worker(connection, destination, "worker1", startSignal, doneSignal, counters, messageCount, messageGroups, worker1Started); - messageCount.put("worker2", 0); - messageGroups.put("worker2", new HashSet()); - Worker worker2 = new Worker(connection, destination, "worker2", startSignal, doneSignal, counters, messageCount, messageGroups, worker2Started); - - new Thread(worker1).start(); - - for (int i = 0; i < perBatch; i++) { - Message msga = session.createTextMessage("hello c"); - msga.setStringProperty("JMSXGroupID", "A"); - producer.send(msga); - - Message msgb = session.createTextMessage("hello b"); - msgb.setStringProperty("JMSXGroupID", "B"); - producer.send(msgb); - } - - // ensure this chap, late to the party gets a new group - new Thread(worker2).start(); - - // wait for presence before new group - worker2Started.await(); - - for (int i = 0; i < perBatch; i++) { - Message msgc = session.createTextMessage("hello a"); - msgc.setStringProperty("JMSXGroupID", "C"); - producer.send(msgc); - } - - doneSignal.await(); - - log.info("worker1 received " + messageCount.get("worker1") + " messages from groups " + messageGroups.get("worker1")); - assertEquals("worker1 received " + messageCount.get("worker1") + " messages from groups " + messageGroups.get("worker1"), 2 * perBatch, messageCount.get("worker1").intValue()); - assertEquals("worker1 received " + messageCount.get("worker1") + " messages from groups " + messageGroups.get("worker1"), 2, messageGroups.get("worker1").size()); - - log.info("worker2 received " + messageCount.get("worker2") + " messages from groups " + messageGroups.get("worker2")); - assertEquals("worker2 received " + messageCount.get("worker2") + " messages from groups " + messageGroups.get("worker2"), 2 * perBatch, messageCount.get("worker1").intValue()); - assertEquals("worker2 received " + messageCount.get("worker2") + " messages from groups " + messageGroups.get("worker2"), 1, messageGroups.get("worker2").size()); - } - - private static final class Worker implements Runnable { - - private Connection connection = null; - private Destination queueName = null; - private String workerName = null; - private CountDownLatch startSignal = null; - private CountDownLatch doneSignal = null; - private CountDownLatch workerStarted = null; - private int[] counters = null; - private final HashMap messageCount; - private final HashMap> messageGroups; - - private Worker(Connection connection, - Destination queueName, - String workerName, - CountDownLatch startSignal, - CountDownLatch doneSignal, - int[] counters, - HashMap messageCount, - HashMap> messageGroups, - CountDownLatch workerStarted) { - this.connection = connection; - this.queueName = queueName; - this.workerName = workerName; - this.startSignal = startSignal; - this.doneSignal = doneSignal; - this.counters = counters; - this.messageCount = messageCount; - this.messageGroups = messageGroups; - this.workerStarted = workerStarted; - } - - private void update(String group) { - int msgCount = messageCount.get(workerName); - messageCount.put(workerName, msgCount + 1); - Set groups = messageGroups.get(workerName); - groups.add(group); - messageGroups.put(workerName, groups); - } - - @Override - public void run() { - - try { - startSignal.await(); - log.info(workerName); - Session sess = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = sess.createConsumer(queueName); - workerStarted.countDown(); - - while (true) { - if (counters[0] == 0 && counters[1] == 0 && counters[2] == 0) { - doneSignal.countDown(); - log.info(workerName + " done..."); - break; - } - - Message msg = consumer.receive(500); - if (msg == null) - continue; - - msg.acknowledge(); - - String group = msg.getStringProperty("JMSXGroupID"); - msg.getBooleanProperty("JMSXGroupFirstForConsumer"); - - if ("A".equals(group)) { - --counters[0]; - update(group); - } else if ("B".equals(group)) { - --counters[1]; - update(group); - } else if ("C".equals(group)) { - --counters[2]; - update(group); - } else { - log.warn(workerName + ", unknown group"); - } - if (counters[0] != 0 || counters[1] != 0 || counters[2] != 0) { - msg.acknowledge(); - } - } - consumer.close(); - sess.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupNewConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupNewConsumerTest.java deleted file mode 100644 index 75d10eeb74..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupNewConsumerTest.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.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.util.concurrent.CountDownLatch; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/* - * Test plan: - * Producer: publish messages into a queue, with three message groups - * Consumer1: created before any messages are created - * Consumer2: created after consumer1 has processed one message from each message group - * - * All three groups are handled by to consumer1, so consumer2 should not get any messages. - * See bug AMQ-2016: Message grouping fails when consumers are added - */ -public class MessageGroupNewConsumerTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(MessageGroupNewConsumerTest.class); - private Connection connection; - // Released after the messages are created - private CountDownLatch latchMessagesCreated = new CountDownLatch(1); - // Released after one message from each group is consumed - private CountDownLatch latchGroupsAcquired = new CountDownLatch(1); - - private static final String[] groupNames = {"GrA", "GrB", "GrC"}; - private int messagesSent, messagesRecvd1, messagesRecvd2; - // with the prefetch too high, this bug is not realized - private static final String connStr = "vm://localhost?broker.persistent=false&broker.useJmx=false&jms.prefetchPolicy.all=1"; - - public void testNewConsumer() throws JMSException, InterruptedException { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connStr); - connection = factory.createConnection(); - connection.start(); - final String queueName = this.getClass().getSimpleName(); - final Thread producerThread = new Thread() { - @Override - public void run() { - try { - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Queue queue = session.createQueue(queueName); - MessageProducer prod = session.createProducer(queue); - for (int i = 0; i < 10; i++) { - for (String group : groupNames) { - Message message = generateMessage(session, group, i + 1); - prod.send(message); - session.commit(); - messagesSent++; - } - LOG.info("Sent message seq " + (i + 1)); - if (i == 0) { - latchMessagesCreated.countDown(); - } - if (i == 2) { - LOG.info("Prod: Waiting for groups"); - latchGroupsAcquired.await(); - } - Thread.sleep(20); - } - LOG.info(messagesSent + " messages sent"); - prod.close(); - session.close(); - } catch (Exception e) { - LOG.error("Producer failed", e); - } - } - }; - final Thread consumerThread1 = new Thread() { - @Override - public void run() { - try { - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Queue queue = session.createQueue(queueName); - MessageConsumer con1 = session.createConsumer(queue); - latchMessagesCreated.await(); - while (true) { - Message message = con1.receive(1000); - if (message == null) - break; - LOG.info("Con1 got message " + formatMessage(message)); - session.commit(); - messagesRecvd1++; - // since we get the messages in order, the first few messages will be one from each group - // after we get one from each group, start the other consumer - if (messagesRecvd1 == groupNames.length) { - LOG.info("All groups acquired"); - latchGroupsAcquired.countDown(); - Thread.sleep(1000); - } - Thread.sleep(50); - } - LOG.info(messagesRecvd1 + " messages received by consumer1"); - con1.close(); - session.close(); - } catch (Exception e) { - LOG.error("Consumer 1 failed", e); - } - } - }; - final Thread consumerThread2 = new Thread() { - @Override - public void run() { - try { - latchGroupsAcquired.await(); - while (consumerThread1.isAlive()) { - LOG.info("(re)starting consumer2"); - Session session = connection.createSession(true, Session.SESSION_TRANSACTED); - Queue queue = session.createQueue(queueName); - MessageConsumer con2 = session.createConsumer(queue); - while (true) { - Message message = con2.receive(500); - if (message == null) - break; - LOG.info("Con2 got message " + formatMessage(message)); - session.commit(); - messagesRecvd2++; - Thread.sleep(50); - } - con2.close(); - session.close(); - } - LOG.info(messagesRecvd2 + " messages received by consumer2"); - } catch (Exception e) { - LOG.error("Consumer 2 failed", e); - } - } - }; - consumerThread2.start(); - consumerThread1.start(); - producerThread.start(); - // wait for threads to finish - producerThread.join(); - consumerThread1.join(); - consumerThread2.join(); - connection.close(); - // check results - assertEquals("consumer 2 should not get any messages", 0, messagesRecvd2); - assertEquals("consumer 1 should get all the messages", messagesSent, messagesRecvd1); - assertTrue("producer failed to send any messages", messagesSent > 0); - } - - public Message generateMessage(Session session, String groupId, int seq) throws JMSException { - TextMessage m = session.createTextMessage(); - m.setJMSType("TEST_MESSAGE"); - m.setStringProperty("JMSXGroupID", groupId); - m.setIntProperty("JMSXGroupSeq", seq); - m.setText(""); - return m; - } - - public String formatMessage(Message m) { - try { - return m.getStringProperty("JMSXGroupID") + "-" + m.getIntProperty("JMSXGroupSeq") + "-" + m.getBooleanProperty("JMSXGroupFirstForConsumer"); - } catch (Exception e) { - return e.getClass().getSimpleName() + ": " + e.getMessage(); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupReconnectDistributionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupReconnectDistributionTest.java deleted file mode 100644 index 9376935308..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageGroupReconnectDistributionTest.java +++ /dev/null @@ -1,218 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Random; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQQueue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -@RunWith(Parameterized.class) -public class MessageGroupReconnectDistributionTest { - - public static final Logger LOG = LoggerFactory.getLogger(MessageGroupReconnectDistributionTest.class); - final Random random = new Random(); - protected Connection connection; - protected Session session; - protected MessageProducer producer; - protected ActiveMQQueue destination = new ActiveMQQueue("GroupQ"); - protected TransportConnector connector; - ActiveMQConnectionFactory connFactory; - BrokerService broker; - int numMessages = 10000; - int groupSize = 10; - int batchSize = 20; - - @Parameterized.Parameter(0) - public int numConsumers = 4; - - @Parameterized.Parameter(1) - public boolean consumerPriority = true; - - @Parameterized.Parameters(name = "numConsumers={0},consumerPriority={1}") - public static Iterable combinations() { - return Arrays.asList(new Object[][]{{4, true}, {10, true}}); - } - - @Before - public void setUp() throws Exception { - broker = createBroker(); - broker.start(); - connFactory = new ActiveMQConnectionFactory(connector.getConnectUri() + "?jms.prefetchPolicy.all=200"); - connFactory.setWatchTopicAdvisories(false); - connection = connFactory.createConnection(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - producer = session.createProducer(destination); - connection.start(); - } - - protected BrokerService createBroker() throws Exception { - BrokerService service = new BrokerService(); - service.setAdvisorySupport(false); - service.setPersistent(false); - service.setUseJmx(true); - - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policy = new PolicyEntry(); - policy.setUseConsumerPriority(consumerPriority); - policy.setMessageGroupMapFactoryType("cached?cacheSize=" + (numConsumers - 1)); - policyMap.setDefaultEntry(policy); - service.setDestinationPolicy(policyMap); - - connector = service.addConnector("tcp://localhost:0"); - return service; - } - - @After - public void tearDown() throws Exception { - producer.close(); - session.close(); - connection.close(); - broker.stop(); - } - - @Test(timeout = 5 * 60 * 1000) - public void testReconnect() throws Exception { - - final AtomicLong totalConsumed = new AtomicLong(0); - - ExecutorService executorService = Executors.newFixedThreadPool(numConsumers); - final ArrayList consumedCounters = new ArrayList<>(numConsumers); - final ArrayList batchCounters = new ArrayList<>(numConsumers); - - for (int i = 0; i < numConsumers; i++) { - consumedCounters.add(new AtomicLong(0L)); - batchCounters.add(new AtomicLong(0L)); - - final int id = i; - executorService.submit(new Runnable() { - int getBatchSize() { - return (id + 1) * batchSize; - } - - @Override - public void run() { - try { - Session connectionSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - int batchSize = getBatchSize(); - MessageConsumer messageConsumer = connectionSession.createConsumer(destWithPrefetch(destination)); - - Message message; - AtomicLong consumed = consumedCounters.get(id); - AtomicLong batches = batchCounters.get(id); - - LOG.info("Consumer: " + id + ", batchSize:" + batchSize + ", totalConsumed:" + totalConsumed.get() + ", consumed:" + consumed.get()); - - while (totalConsumed.get() < numMessages) { - - message = messageConsumer.receive(10000); - - if (message == null) { - LOG.info("Consumer: " + id + ", batchSize:" + batchSize + ", null message (totalConsumed:" + totalConsumed.get() + ") consumed:" + consumed.get()); - messageConsumer.close(); - - if (totalConsumed.get() == numMessages) { - break; - } else { - batchSize = getBatchSize(); - messageConsumer = connectionSession.createConsumer(destWithPrefetch(destination)); - batches.incrementAndGet(); - continue; - } - } - - consumed.incrementAndGet(); - totalConsumed.incrementAndGet(); - - if (consumed.get() > 0 && consumed.intValue() % batchSize == 0) { - messageConsumer.close(); - batchSize = getBatchSize(); - messageConsumer = connectionSession.createConsumer(destWithPrefetch(destination)); - batches.incrementAndGet(); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - TimeUnit.MILLISECONDS.sleep(200); - } - - TimeUnit.SECONDS.sleep(1); - produceMessages(numMessages); - - executorService.shutdown(); - assertTrue("threads done on time", executorService.awaitTermination(10, TimeUnit.MINUTES)); - - assertEquals("All consumed", numMessages, totalConsumed.intValue()); - - LOG.info("Distribution: " + consumedCounters); - LOG.info("Batches: " + batchCounters); - - double max = consumedCounters.get(0).longValue() * 1.5; - double min = consumedCounters.get(0).longValue() * 0.5; - - for (AtomicLong l : consumedCounters) { - assertTrue("Even +/- 50% distribution on consumed:" + consumedCounters + ", outlier:" + l.get(), l.longValue() < max && l.longValue() > min); - } - } - - private Destination destWithPrefetch(ActiveMQQueue destination) throws Exception { - return destination; - } - - private void produceMessages(int numMessages) throws JMSException { - int groupID = 0; - for (int i = 0; i < numMessages; i++) { - if (i > 0 && i % groupSize == 0) { - groupID++; - } - TextMessage msga = session.createTextMessage("hello " + i); - msga.setStringProperty("JMSXGroupID", "Group-" + groupID); - producer.send(msga); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageReroutingTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageReroutingTest.java deleted file mode 100644 index 40f1c20a2e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MessageReroutingTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Destination; -import javax.jms.MessageConsumer; - -import junit.framework.Test; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.util.MessageIdList; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.ClassPathResource; - -public class MessageReroutingTest extends JmsMultipleBrokersTestSupport { - - private static final transient Logger LOG = LoggerFactory.getLogger(MessageReroutingTest.class); - - public Destination dest; - public static final int MESSAGE_COUNT = 50; - - @Override - protected void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - - createBroker(new ClassPathResource("org/apache/activemq/usecases/rerouting-activemq-D.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/rerouting-activemq-C.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/rerouting-activemq-B.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/rerouting-activemq-A.xml")); - - brokers.get("broker-A").broker.waitUntilStarted(); - } - - public void initCombos() { - addCombinationValues("dest", new Object[]{new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST")}); - } - - public void testMessageRerouting() throws Exception { - MessageConsumer consumer = createConsumer("broker-D", dest); - - MessageIdList received = getConsumerMessages("broker-D", consumer); - - Thread.sleep(2000); //wait for subs to propagate - - // send/receive messages - sendMessages("broker-A", dest, MESSAGE_COUNT); - received.waitForMessagesToArrive(MESSAGE_COUNT); - LOG.info("received " + received.getMessageCount() + " messages"); - assertEquals(MESSAGE_COUNT, received.getMessageCount()); - - brokers.get("broker-B").broker.stop(); - brokers.get("broker-B").broker.waitUntilStopped(); - Thread.sleep(2000); - - // ensure send/receive still works - sendMessages("broker-A", dest, MESSAGE_COUNT); - received.waitForMessagesToArrive(MESSAGE_COUNT); - LOG.info("received " + received.getMessageCount() + " messages"); - assertTrue("Didn't receive any more messages " + received.getMessageCount(), received.getMessageCount() > MESSAGE_COUNT); - - } - - public static Test suite() { - return suite(MessageReroutingTest.class); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MultiBrokersMultiClientsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MultiBrokersMultiClientsTest.java deleted file mode 100644 index 7e66b7dd96..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MultiBrokersMultiClientsTest.java +++ /dev/null @@ -1,167 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Destination; -import javax.jms.MessageConsumer; -import java.lang.Thread.UncaughtExceptionHandler; -import java.net.URI; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.util.MessageIdList; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class MultiBrokersMultiClientsTest extends JmsMultipleBrokersTestSupport implements UncaughtExceptionHandler { - - public static final int BROKER_COUNT = 6; // number of brokers to network - public static final int CONSUMER_COUNT = 25; // consumers per broker - public static final int PRODUCER_COUNT = 3; // producers per broker - public static final int MESSAGE_COUNT = 20; // messages per producer - - private static final Logger LOG = LoggerFactory.getLogger(MultiBrokersMultiClientsTest.class); - - protected Map consumerMap; - final Map unhandeledExceptions = new HashMap<>(); - - public void testTopicAllConnected() throws Exception { - bridgeAllBrokers(); - startAllBrokers(); - waitForBridgeFormation(); - - // Setup topic destination - Destination dest = createDestination("TEST.FOO", true); - - CountDownLatch latch = new CountDownLatch(BROKER_COUNT * PRODUCER_COUNT * BROKER_COUNT * CONSUMER_COUNT * MESSAGE_COUNT); - - // Setup consumers - for (int i = 1; i <= BROKER_COUNT; i++) { - for (int j = 0; j < CONSUMER_COUNT; j++) { - consumerMap.put("Consumer:" + i + ":" + j, createConsumer("Broker" + i, dest, latch)); - } - } - - // wait for consumers to get propagated - for (int i = 1; i <= BROKER_COUNT; i++) { - // all consumers on the remote brokers look like 1 consumer to the local broker. - assertConsumersConnect("Broker" + i, dest, (BROKER_COUNT - 1) + CONSUMER_COUNT, 65000); - } - - // Send messages - for (int i = 1; i <= BROKER_COUNT; i++) { - for (int j = 0; j < PRODUCER_COUNT; j++) { - sendMessages("Broker" + i, dest, MESSAGE_COUNT); - } - } - - assertTrue("Missing " + latch.getCount() + " messages", latch.await(45, TimeUnit.SECONDS)); - - // Get message count - for (int i = 1; i <= BROKER_COUNT; i++) { - for (int j = 0; j < CONSUMER_COUNT; j++) { - MessageIdList msgs = getConsumerMessages("Broker" + i, consumerMap.get("Consumer:" + i + ":" + j)); - assertEquals(BROKER_COUNT * PRODUCER_COUNT * MESSAGE_COUNT, msgs.getMessageCount()); - } - } - - assertNoUnhandeledExceptions(); - } - - private void assertNoUnhandeledExceptions() { - for (Entry e : unhandeledExceptions.entrySet()) { - LOG.error("Thread:" + e.getKey() + " Had unexpected: " + e.getValue()); - } - assertTrue("There are no unhandelled exceptions, see: log for detail on: " + unhandeledExceptions, unhandeledExceptions.isEmpty()); - } - - public void testQueueAllConnected() throws Exception { - bridgeAllBrokers(); - startAllBrokers(); - this.waitForBridgeFormation(); - - // Setup topic destination - Destination dest = createDestination("TEST.FOO", false); - - CountDownLatch latch = new CountDownLatch(BROKER_COUNT * PRODUCER_COUNT * MESSAGE_COUNT); - - // Setup consumers - for (int i = 1; i <= BROKER_COUNT; i++) { - for (int j = 0; j < CONSUMER_COUNT; j++) { - consumerMap.put("Consumer:" + i + ":" + j, createConsumer("Broker" + i, dest, latch)); - } - } - - // wait for consumers to get propagated - for (int i = 1; i <= BROKER_COUNT; i++) { - // all consumers on the remote brokers look like 1 consumer to the local broker. - assertConsumersConnect("Broker" + i, dest, (BROKER_COUNT - 1) + CONSUMER_COUNT, 65000); - } - - // Send messages - for (int i = 1; i <= BROKER_COUNT; i++) { - for (int j = 0; j < PRODUCER_COUNT; j++) { - sendMessages("Broker" + i, dest, MESSAGE_COUNT); - } - } - - // Wait for messages to be delivered - assertTrue("Missing " + latch.getCount() + " messages", latch.await(45, TimeUnit.SECONDS)); - - // Get message count - int totalMsg = 0; - for (int i = 1; i <= BROKER_COUNT; i++) { - for (int j = 0; j < CONSUMER_COUNT; j++) { - MessageIdList msgs = getConsumerMessages("Broker" + i, consumerMap.get("Consumer:" + i + ":" + j)); - totalMsg += msgs.getMessageCount(); - } - } - assertEquals(BROKER_COUNT * PRODUCER_COUNT * MESSAGE_COUNT, totalMsg); - - assertNoUnhandeledExceptions(); - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - - unhandeledExceptions.clear(); - Thread.setDefaultUncaughtExceptionHandler(this); - - // Setup n brokers - for (int i = 1; i <= BROKER_COUNT; i++) { - createBroker(new URI("broker:()/Broker" + i + "?persistent=false&useJmx=false")); - } - - consumerMap = new HashMap<>(); - } - - @Override - public void uncaughtException(Thread t, Throwable e) { - synchronized (unhandeledExceptions) { - unhandeledExceptions.put(t, e); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MultiBrokersMultiClientsUsingTcpTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MultiBrokersMultiClientsUsingTcpTest.java deleted file mode 100644 index ab705604ba..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MultiBrokersMultiClientsUsingTcpTest.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.activemq.usecases; - -import java.net.URI; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.network.DemandForwardingBridge; -import org.apache.activemq.network.NetworkBridgeConfiguration; -import org.apache.activemq.transport.TransportFactory; - -/** - * - */ -public class MultiBrokersMultiClientsUsingTcpTest extends MultiBrokersMultiClientsTest { - - protected List bridges; - - protected void bridgeAllBrokers(String groupName) throws Exception { - for (int i = 1; i <= BROKER_COUNT; i++) { - for (int j = 1; j <= BROKER_COUNT; j++) { - if (i != j) { - bridgeBrokers("Broker" + i, "Broker" + j); - } - } - } - - maxSetupTime = 5000; - } - - protected void bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker) throws Exception { - List remoteTransports = remoteBroker.getTransportConnectors(); - List localTransports = localBroker.getTransportConnectors(); - - URI remoteURI; - URI localURI; - if (!remoteTransports.isEmpty() && !localTransports.isEmpty()) { - remoteURI = remoteTransports.get(0).getConnectUri(); - localURI = localTransports.get(0).getConnectUri(); - - // Ensure that we are connecting using tcp - if (remoteURI.toString().startsWith("tcp:") && localURI.toString().startsWith("tcp:")) { - NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); - config.setBrokerName(localBroker.getBrokerName()); - DemandForwardingBridge bridge = new DemandForwardingBridge(config, TransportFactory.connect(localURI), TransportFactory.connect(remoteURI)); - bridge.setBrokerService(localBroker); - bridges.add(bridge); - - bridge.start(); - } else { - throw new Exception("Remote broker or local broker is not using tcp connectors"); - } - } else { - throw new Exception("Remote broker or local broker has no registered connectors."); - } - } - - @Override - public void setUp() throws Exception { - super.setUp(); - - // Assign a tcp connector to each broker - int j = 0; - for (Iterator i = brokers.values().iterator(); i.hasNext(); ) { - i.next().broker.addConnector("tcp://localhost:" + (61616 + j++)); - } - - bridges = new ArrayList<>(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MulticastDiscoveryOnFaultyNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MulticastDiscoveryOnFaultyNetworkTest.java deleted file mode 100644 index b316ba7b92..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MulticastDiscoveryOnFaultyNetworkTest.java +++ /dev/null @@ -1,130 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Destination; -import javax.jms.MessageConsumer; -import javax.jms.TextMessage; -import java.net.URI; -import java.util.List; - -import junit.framework.Test; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.network.DiscoveryNetworkConnector; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.util.MessageIdList; - -public class MulticastDiscoveryOnFaultyNetworkTest extends JmsMultipleBrokersTestSupport { - - protected static final int MESSAGE_COUNT = 200; - private static final String HUB = "HubBroker"; - private static final String SPOKE = "SpokeBroker"; - public boolean useDuplexNetworkBridge = true; - public boolean useStaticDiscovery = false; - - public void initCombosForTestSendOnAFaultyTransport() { - addCombinationValues("useDuplexNetworkBridge", new Object[]{Boolean.TRUE, Boolean.FALSE}); - addCombinationValues("useStaticDiscovery", new Object[]{Boolean.TRUE, Boolean.FALSE}); - } - - public void testSendOnAFaultyTransport() throws Exception { - bridgeBrokers(SPOKE, HUB); - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - MessageConsumer client = createConsumer(HUB, dest); - - // allow subscription information to flow back to Spoke - sleep(600); - - // Send messages - sendMessages(SPOKE, dest, MESSAGE_COUNT); - - MessageIdList msgs = getConsumerMessages(HUB, client); - msgs.setMaximumDuration(200000L); - msgs.waitForMessagesToArrive(MESSAGE_COUNT); - - assertTrue("At least message " + MESSAGE_COUNT + - " must be received, duplicates are expected, count=" + msgs.getMessageCount(), MESSAGE_COUNT <= msgs.getMessageCount()); - } - - @Override - protected void startAllBrokers() throws Exception { - // Ensure HUB is started first so bridge will be active from the get go - BrokerItem brokerItem = brokers.get(HUB); - brokerItem.broker.start(); - brokerItem = brokers.get(SPOKE); - brokerItem.broker.start(); - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - final String options = "?persistent=false&useJmx=false&deleteAllMessagesOnStartup=true"; - createBroker(new URI("broker:(tcpfaulty://localhost:61617)/" + HUB + options)); - createBroker(new URI("broker:(tcpfaulty://localhost:61616)/" + SPOKE + options)); - } - - public static Test suite() { - return suite(MulticastDiscoveryOnFaultyNetworkTest.class); - } - - @Override - protected void onSend(int i, TextMessage msg) { - sleep(50); - } - - private void sleep(int milliSecondTime) { - try { - Thread.sleep(milliSecondTime); - } catch (InterruptedException igonred) { - } - } - - @Override - protected NetworkConnector bridgeBrokers(BrokerService localBroker, - BrokerService remoteBroker, - boolean dynamicOnly, - int networkTTL, - boolean conduit, - boolean failover) throws Exception { - String networkDisoveryUrlString = useStaticDiscovery ? "static:(" + remoteBroker.getTransportConnectors().get(0).getPublishableConnectString() + ")?useExponentialBackOff=false" : "multicast://default?group=TESTERIC&useLocalHost=false"; - - DiscoveryNetworkConnector connector = new DiscoveryNetworkConnector(new URI(networkDisoveryUrlString)); - connector.setDynamicOnly(dynamicOnly); - connector.setNetworkTTL(networkTTL); - connector.setDuplex(useDuplexNetworkBridge); - maxSetupTime = 2000; - if (!useStaticDiscovery) { - List transportConnectors = remoteBroker.getTransportConnectors(); - if (!transportConnectors.isEmpty()) { - TransportConnector mCastTrpConnector = (transportConnectors.get(0)); - mCastTrpConnector.setDiscoveryUri(new URI("multicast://default?group=TESTERIC")); - } - } - localBroker.addNetworkConnector(connector); - return connector; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MyObject.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MyObject.java deleted file mode 100644 index a8583bfbc1..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/MyObject.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.activemq.usecases; - -import java.io.IOException; -import java.io.Serializable; -import java.util.concurrent.atomic.AtomicInteger; - -public class MyObject implements Serializable { - - private static final long serialVersionUID = -2505777188753549398L; - - private String message; - private final AtomicInteger writeObjectCalled = new AtomicInteger(0); - private final AtomicInteger readObjectCalled = new AtomicInteger(0); - private final AtomicInteger readObjectNoDataCalled = new AtomicInteger(0); - - public MyObject(String message) { - this.setMessage(message); - } - - public void setMessage(String message) { - this.message = message; - } - - public String getMessage() { - return message; - } - - private void writeObject(java.io.ObjectOutputStream out) throws IOException { - writeObjectCalled.incrementAndGet(); - out.defaultWriteObject(); - } - - private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - readObjectCalled.incrementAndGet(); - } - - public int getWriteObjectCalled() { - return writeObjectCalled.get(); - } - - public int getReadObjectCalled() { - return readObjectCalled.get(); - } - - public int getReadObjectNoDataCalled() { - return readObjectNoDataCalled.get(); - } -} - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkAsyncStartTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkAsyncStartTest.java deleted file mode 100644 index ccd3d7e5eb..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkAsyncStartTest.java +++ /dev/null @@ -1,123 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import java.net.URI; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.network.DiscoveryNetworkConnector; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.util.SocketProxy; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class NetworkAsyncStartTest extends JmsMultipleBrokersTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(NetworkAsyncStartTest.class); - - private String brokerBUri = "tcp://localhost:61617"; - private String brokerCUri = "tcp://localhost:61618"; - int bridgeCount = 0; - - public void testAsyncNetworkStartup() throws Exception { - - BrokerService brokerA = brokers.get("BrokerA").broker; - bridgeBroker(brokerA, brokerBUri); - bridgeBroker(brokerA, brokerCUri); - - LOG.info("starting A, no blocking on failed network connectors"); - brokerA.start(); - - LOG.info("starting C transport connector"); - BrokerService brokerC = brokers.get("BrokerC").broker; - brokerC.addConnector(brokerCUri); - brokerC.start(); - - assertTrue("got bridge to C", waitForBridgeFormation(brokerA, 1, 1)); - LOG.info("Got bridge A->C"); - - LOG.info("starting B transport connector"); - BrokerService brokerB = brokers.get("BrokerB").broker; - brokerB.addConnector(brokerBUri); - brokerB.start(); - - assertTrue("got bridge to B", waitForBridgeFormation(brokerA, 1, 0)); - assertTrue("got bridge to B&C", waitForBridgeFormation(brokerA, 1, 1)); - } - - public void testAsyncNetworkStartupWithSlowConnectionCreation() throws Exception { - - final BrokerService brokerA = brokers.get("BrokerA").broker; - - SocketProxy proxyToB = new SocketProxy(); - // don't accept any connections so limited to one connection with backlog - proxyToB.setPauseAtStart(true); - proxyToB.setAcceptBacklog(1); - proxyToB.setTarget(new URI(brokerBUri)); - proxyToB.open(); - bridgeBroker(brokerA, proxyToB.getUrl().toString()); - bridgeBroker(brokerA, proxyToB.getUrl().toString()); - bridgeBroker(brokerA, proxyToB.getUrl().toString()); - bridgeBroker(brokerA, proxyToB.getUrl().toString()); - bridgeBroker(brokerA, proxyToB.getUrl().toString()); - bridgeBroker(brokerA, proxyToB.getUrl().toString()); - bridgeBroker(brokerA, proxyToB.getUrl().toString()); - bridgeBroker(brokerA, brokerCUri); - - Executor e = Executors.newCachedThreadPool(); - e.execute(new Runnable() { - @Override - public void run() { - LOG.info("starting A"); - try { - brokerA.setNetworkConnectorStartAsync(true); - brokerA.start(); - } catch (Exception e) { - LOG.error("start failed", e); - } - } - }); - - LOG.info("starting transport connector on C"); - BrokerService brokerC = brokers.get("BrokerC").broker; - brokerC.addConnector(brokerCUri); - brokerC.start(); - - final long maxWaitMillis = 20 * 1000; - assertTrue("got bridge to C in 10 seconds", waitForBridgeFormation(brokerA, 1, 7, maxWaitMillis)); - } - - private void bridgeBroker(BrokerService localBroker, String remoteURI) throws Exception { - String uri = "static:(" + remoteURI + ")"; - NetworkConnector connector = new DiscoveryNetworkConnector(new URI(uri)); - connector.setName("bridge-" + bridgeCount++); - localBroker.addNetworkConnector(connector); - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - // initially with no tcp transport connector - createBroker(new URI("broker:()BrokerA?persistent=false&useJmx=false")); - createBroker(new URI("broker:()BrokerB?persistent=false&useJmx=false")); - createBroker(new URI("broker:()BrokerC?persistent=false&useJmx=false")); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkBridgeProducerFlowControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkBridgeProducerFlowControlTest.java deleted file mode 100644 index 8f8b8b4b2c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkBridgeProducerFlowControlTest.java +++ /dev/null @@ -1,347 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.usecases; - -import javax.jms.MessageConsumer; -import java.net.URI; -import java.util.Vector; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - -import junit.framework.Test; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.util.MessageIdList; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Assert; - -/** - * This test demonstrates and verifies the behaviour of a network bridge when it - * forwards a message to a queue that is full and producer flow control is - * enabled. - *
- * The expected behaviour is that the bridge will stop forwarding messages to - * the full queue once the associated demand consumer's prefetch is full, but - * will continue to forward messages to the other queues that are not full. - *
- * In actuality, a message that is sent asynchronously to a local queue, - * but blocked by producer flow control on the remote queue, will stop the - * bridge from forwarding all subsequent messages, even those destined for - * remote queues that are not full. In the same scenario, but with a message - * that is sent synchronously to the local queue, the bridge continues - * forwarding messages to remote queues that are not full. - *
- * This test demonstrates the differing behaviour via the following scenario: - *

    - *
  • broker0, designated as the local broker, produces messages to two shared - * queues - *
  • broker1, designated as the remote broker, has two consumers: the first - * consumes from one of the shared queues as fast as possible, the second - * consumes from the other shared queue with an artificial processing delay for - * each message - *
  • broker0 forwards messages to broker1 over a TCP-based network bridge - * with a demand consumer prefetch of 1 - *
  • broker1's consumers have a prefetch of 1 - *
  • broker1's "slow consumer" queue has a memory limit that triggers - * producer flow control once the queue contains a small number of messages - *
- * In this scenario, since broker1's consumers have a prefetch of 1, the "slow - * consumer" queue will quickly become full and trigger producer flow control. - * The "fast consumer" queue is unlikely to become full. Since producer flow - * control on the "slow consumer" queue should not affect the "fast consumer" - * queue, the expectation is that the fast consumer in broker1 will finish - * processing all its messages well ahead of the slow consumer. - *
- * The difference between expected and actual behaviour is demonstrated by - * changing the messages produced by broker0 from persistent to non-persistent. - * With persistent messages, broker0 dispatches synchronously and the expected - * behaviour is observed (i.e., the fast consumer on broker1 is much faster than - * the slow consumer). With non-persistent messages, broker0 dispatches - * asynchronously and the expected behaviour is not observed (i.e., the - * fast consumer is only marginally faster than the slow consumer). - *
- * Since the expected behaviour may be desirable for both persistent and - * non-persistent messages, this test also demonstrates an enhancement to the - * network bridge configuration: isAlwaysSendSync. When false the - * bridge operates as originally observed. When true, the bridge - * operates with the same behaviour as was originally observed with persistent - * messages, for both persistent and non-persistent messages. - *
- * https://issues.apache.org/jira/browse/AMQ-3331 - * - * @author schow - */ -public class NetworkBridgeProducerFlowControlTest extends JmsMultipleBrokersTestSupport { - - // Protect against hanging test. - private static final long MAX_TEST_TIME = 120000; - - private static final Log LOG = LogFactory.getLog(NetworkBridgeProducerFlowControlTest.class); - - // Combo flag set to true/false by the test framework. - public boolean persistentTestMessages; - public boolean networkIsAlwaysSendSync; - - private Vector exceptions = new Vector<>(); - - public static Test suite() { - return suite(NetworkBridgeProducerFlowControlTest.class); - } - - public void initCombosForTestFastAndSlowRemoteConsumers() { - addCombinationValues("persistentTestMessages", new Object[]{Boolean.valueOf(true), Boolean.valueOf(false)}); - addCombinationValues("networkIsAlwaysSendSync", new Object[]{Boolean.valueOf(true), Boolean.valueOf(false)}); - } - - @Override - protected void setUp() throws Exception { - setAutoFail(true); - setMaxTestTime(MAX_TEST_TIME); - super.setUp(); - } - - /** - * This test is parameterized by {@link #persistentTestMessages}, which - * determines whether the producer on broker0 sends persistent or - * non-persistent messages, and {@link #networkIsAlwaysSendSync}, which - * determines how the bridge will forward both persistent and non-persistent - * messages to broker1. - * - * @see #initCombosForTestFastAndSlowRemoteConsumers() - */ - public void testFastAndSlowRemoteConsumers() throws Exception { - final int NUM_MESSAGES = 100; - final long TEST_MESSAGE_SIZE = 1024; - final long SLOW_CONSUMER_DELAY_MILLIS = 100; - - // Consumer prefetch is disabled for broker1's consumers. - final ActiveMQQueue SLOW_SHARED_QUEUE = new ActiveMQQueue(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".slow.shared?consumer.prefetchSize=1"); - - final ActiveMQQueue FAST_SHARED_QUEUE = new ActiveMQQueue(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".fast.shared?consumer.prefetchSize=1"); - - // Start a local and a remote broker. - createBroker(new URI("broker:(tcp://localhost:0" + ")?brokerName=broker0&persistent=false&useJmx=true")); - BrokerService remoteBroker = createBroker(new URI("broker:(tcp://localhost:0" + ")?brokerName=broker1&persistent=false&useJmx=true")); - - // Set a policy on the remote broker that limits the maximum size of the - // slow shared queue. - PolicyEntry policyEntry = new PolicyEntry(); - policyEntry.setMemoryLimit(5 * TEST_MESSAGE_SIZE); - PolicyMap policyMap = new PolicyMap(); - policyMap.put(SLOW_SHARED_QUEUE, policyEntry); - remoteBroker.setDestinationPolicy(policyMap); - - // Create an outbound bridge from the local broker to the remote broker. - // The bridge is configured with the remoteDispatchType enhancement. - NetworkConnector nc = bridgeBrokers("broker0", "broker1"); - nc.setAlwaysSyncSend(networkIsAlwaysSendSync); - nc.setPrefetchSize(1); - - startAllBrokers(); - waitForBridgeFormation(); - - // Send the test messages to the local broker's shared queues. The - // messages are either persistent or non-persistent to demonstrate the - // difference between synchronous and asynchronous dispatch. - persistentDelivery = persistentTestMessages; - sendMessages("broker0", FAST_SHARED_QUEUE, NUM_MESSAGES); - sendMessages("broker0", SLOW_SHARED_QUEUE, NUM_MESSAGES); - - // Start two asynchronous consumers on the remote broker, one for each - // of the two shared queues, and keep track of how long it takes for - // each of the consumers to receive all the messages. - final CountDownLatch fastConsumerLatch = new CountDownLatch(NUM_MESSAGES); - final CountDownLatch slowConsumerLatch = new CountDownLatch(NUM_MESSAGES); - - final long startTimeMillis = System.currentTimeMillis(); - final AtomicLong fastConsumerTime = new AtomicLong(); - final AtomicLong slowConsumerTime = new AtomicLong(); - - Thread fastWaitThread = new Thread() { - @Override - public void run() { - try { - fastConsumerLatch.await(); - fastConsumerTime.set(System.currentTimeMillis() - startTimeMillis); - } catch (InterruptedException ex) { - exceptions.add(ex); - Assert.fail(ex.getMessage()); - } - } - }; - - Thread slowWaitThread = new Thread() { - @Override - public void run() { - try { - slowConsumerLatch.await(); - slowConsumerTime.set(System.currentTimeMillis() - startTimeMillis); - } catch (InterruptedException ex) { - exceptions.add(ex); - Assert.fail(ex.getMessage()); - } - } - }; - - fastWaitThread.start(); - slowWaitThread.start(); - - createConsumer("broker1", FAST_SHARED_QUEUE, fastConsumerLatch); - MessageConsumer slowConsumer = createConsumer("broker1", SLOW_SHARED_QUEUE, slowConsumerLatch); - MessageIdList messageIdList = brokers.get("broker1").consumers.get(slowConsumer); - messageIdList.setProcessingDelay(SLOW_CONSUMER_DELAY_MILLIS); - - fastWaitThread.join(); - slowWaitThread.join(); - - assertTrue("no exceptions on the wait threads:" + exceptions, exceptions.isEmpty()); - - LOG.info("Fast consumer duration (ms): " + fastConsumerTime.get()); - LOG.info("Slow consumer duration (ms): " + slowConsumerTime.get()); - - // Verify the behaviour as described in the description of this class. - if (networkIsAlwaysSendSync) { - Assert.assertTrue(fastConsumerTime.get() < slowConsumerTime.get() / 10); - - } else { - Assert.assertEquals(persistentTestMessages, fastConsumerTime.get() < slowConsumerTime.get() / 10); - } - } - - public void testSendFailIfNoSpaceDoesNotBlockQueueNetwork() throws Exception { - // Consumer prefetch is disabled for broker1's consumers. - final ActiveMQQueue SLOW_SHARED_QUEUE = new ActiveMQQueue(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".slow.shared?consumer.prefetchSize=1"); - - final ActiveMQQueue FAST_SHARED_QUEUE = new ActiveMQQueue(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".fast.shared?consumer.prefetchSize=1"); - - doTestSendFailIfNoSpaceDoesNotBlockNetwork(SLOW_SHARED_QUEUE, FAST_SHARED_QUEUE); - } - - public void testSendFailIfNoSpaceDoesNotBlockTopicNetwork() throws Exception { - // Consumer prefetch is disabled for broker1's consumers. - final ActiveMQTopic SLOW_SHARED_TOPIC = new ActiveMQTopic(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".slow.shared?consumer.prefetchSize=1"); - - final ActiveMQTopic FAST_SHARED_TOPIC = new ActiveMQTopic(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".fast.shared?consumer.prefetchSize=1"); - - doTestSendFailIfNoSpaceDoesNotBlockNetwork(SLOW_SHARED_TOPIC, FAST_SHARED_TOPIC); - } - - public void doTestSendFailIfNoSpaceDoesNotBlockNetwork(ActiveMQDestination slowDestination, - ActiveMQDestination fastDestination) throws Exception { - - final int NUM_MESSAGES = 100; - final long TEST_MESSAGE_SIZE = 1024; - final long SLOW_CONSUMER_DELAY_MILLIS = 100; - - // Start a local and a remote broker. - createBroker(new URI("broker:(tcp://localhost:0" + ")?brokerName=broker0&persistent=false&useJmx=true")); - BrokerService remoteBroker = createBroker(new URI("broker:(tcp://localhost:0" + ")?brokerName=broker1&persistent=false&useJmx=true")); - remoteBroker.getSystemUsage().setSendFailIfNoSpace(true); - - // Set a policy on the remote broker that limits the maximum size of the - // slow shared queue. - PolicyEntry policyEntry = new PolicyEntry(); - policyEntry.setMemoryLimit(5 * TEST_MESSAGE_SIZE); - PolicyMap policyMap = new PolicyMap(); - policyMap.put(slowDestination, policyEntry); - remoteBroker.setDestinationPolicy(policyMap); - - // Create an outbound bridge from the local broker to the remote broker. - // The bridge is configured with the remoteDispatchType enhancement. - NetworkConnector nc = bridgeBrokers("broker0", "broker1"); - nc.setAlwaysSyncSend(true); - nc.setPrefetchSize(1); - - startAllBrokers(); - waitForBridgeFormation(); - - // Start two asynchronous consumers on the remote broker, one for each - // of the two shared queues, and keep track of how long it takes for - // each of the consumers to receive all the messages. - final CountDownLatch fastConsumerLatch = new CountDownLatch(NUM_MESSAGES); - final CountDownLatch slowConsumerLatch = new CountDownLatch(NUM_MESSAGES); - - final long startTimeMillis = System.currentTimeMillis(); - final AtomicLong fastConsumerTime = new AtomicLong(); - final AtomicLong slowConsumerTime = new AtomicLong(); - - Thread fastWaitThread = new Thread() { - @Override - public void run() { - try { - fastConsumerLatch.await(); - fastConsumerTime.set(System.currentTimeMillis() - startTimeMillis); - } catch (InterruptedException ex) { - exceptions.add(ex); - Assert.fail(ex.getMessage()); - } - } - }; - - Thread slowWaitThread = new Thread() { - @Override - public void run() { - try { - slowConsumerLatch.await(); - slowConsumerTime.set(System.currentTimeMillis() - startTimeMillis); - } catch (InterruptedException ex) { - exceptions.add(ex); - Assert.fail(ex.getMessage()); - } - } - }; - - fastWaitThread.start(); - slowWaitThread.start(); - - createConsumer("broker1", fastDestination, fastConsumerLatch); - MessageConsumer slowConsumer = createConsumer("broker1", slowDestination, slowConsumerLatch); - MessageIdList messageIdList = brokers.get("broker1").consumers.get(slowConsumer); - messageIdList.setProcessingDelay(SLOW_CONSUMER_DELAY_MILLIS); - - // Send the test messages to the local broker's shared queues. The - // messages are either persistent or non-persistent to demonstrate the - // difference between synchronous and asynchronous dispatch. - persistentDelivery = false; - sendMessages("broker0", fastDestination, NUM_MESSAGES); - sendMessages("broker0", slowDestination, NUM_MESSAGES); - - fastWaitThread.join(TimeUnit.SECONDS.toMillis(60)); - slowWaitThread.join(TimeUnit.SECONDS.toMillis(60)); - - assertTrue("no exceptions on the wait threads:" + exceptions, exceptions.isEmpty()); - - LOG.info("Fast consumer duration (ms): " + fastConsumerTime.get()); - LOG.info("Slow consumer duration (ms): " + slowConsumerTime.get()); - - assertTrue("fast time set", fastConsumerTime.get() > 0); - assertTrue("slow time set", slowConsumerTime.get() > 0); - - // Verify the behaviour as described in the description of this class. - Assert.assertTrue(fastConsumerTime.get() < slowConsumerTime.get() / 10); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkOfTwentyBrokersTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkOfTwentyBrokersTest.java deleted file mode 100644 index 39e7a6a56b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NetworkOfTwentyBrokersTest.java +++ /dev/null @@ -1,225 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import java.net.URI; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.broker.region.RegionBroker; -import org.apache.activemq.command.BrokerInfo; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.util.ThreadTracker; -import org.apache.activemq.util.Wait; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class NetworkOfTwentyBrokersTest extends JmsMultipleBrokersTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(NetworkOfTwentyBrokersTest.class); - - // This will interconnect all brokers using multicast - @Override - protected void bridgeAllBrokers() throws Exception { - bridgeAllBrokers("TwentyBrokersTest", 1, false, false); - } - - @Override - protected void bridgeAllBrokers(String groupName, int ttl, boolean suppressduplicateQueueSubs) throws Exception { - bridgeAllBrokers(groupName, ttl, suppressduplicateQueueSubs, false); - } - - @Override - protected void bridgeAllBrokers(String groupName, - int ttl, - boolean suppressduplicateQueueSubs, - boolean decreasePriority) throws Exception { - Collection brokerList = brokers.values(); - for (Iterator i = brokerList.iterator(); i.hasNext(); ) { - BrokerService broker = i.next().broker; - List transportConnectors = broker.getTransportConnectors(); - - if (transportConnectors.isEmpty()) { - broker.addConnector(new URI(AUTO_ASSIGN_TRANSPORT)); - transportConnectors = broker.getTransportConnectors(); - } - - TransportConnector transport = transportConnectors.get(0); - if (transport.getDiscoveryUri() == null) { - transport.setDiscoveryUri(new URI("multicast://default?group=" + groupName)); - } - - List networkConnectors = broker.getNetworkConnectors(); - if (networkConnectors.isEmpty()) { - broker.addNetworkConnector("multicast://default?group=" + groupName); - networkConnectors = broker.getNetworkConnectors(); - } - - NetworkConnector nc = networkConnectors.get(0); - nc.setNetworkTTL(ttl); - nc.setSuppressDuplicateQueueSubscriptions(suppressduplicateQueueSubs); - nc.setDecreaseNetworkConsumerPriority(decreasePriority); - } - - // Multicasting may take longer to setup - maxSetupTime = 8000; - } - - @Override - protected BrokerService createBroker(String brokerName) throws Exception { - BrokerService broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.setBrokerName(brokerName); - broker.addConnector(new URI(AUTO_ASSIGN_TRANSPORT)); - brokers.put(brokerName, new BrokerItem(broker)); - - return broker; - } - - /* AMQ-3077 Bug */ - public void testBrokers() throws Exception { - int X = 20; - int i; - - LOG.info("Creating X Brokers"); - for (i = 0; i < X; i++) { - createBroker("Broker" + i); - } - - bridgeAllBrokers(); - startAllBrokers(); - waitForBridgeFormation(X - 1); - - LOG.info("Waiting for complete formation"); - try { - Thread.sleep(20000); - } catch (Exception e) { - } - - verifyPeerBrokerInfos(X - 1); - - LOG.info("Stopping half the brokers"); - for (i = 0; i < X / 2; i++) { - destroyBroker("Broker" + i); - } - - LOG.info("Waiting for complete stop"); - try { - Thread.sleep(20000); - } catch (Exception e) { - } - - verifyPeerBrokerInfos((X / 2) - 1); - - LOG.info("Recreating first half"); - for (i = 0; i < X / 2; i++) { - createBroker("Broker" + i); - } - - bridgeAllBrokers(); - startAllBrokers(); - waitForBridgeFormation(X - 1); - - LOG.info("Waiting for complete reformation"); - try { - Thread.sleep(20000); - } catch (Exception e) { - } - - verifyPeerBrokerInfos(X - 1); - } - - public void testPeerBrokerCountHalfPeer() throws Exception { - createBroker("A"); - createBroker("B"); - bridgeBrokers("A", "B"); - startAllBrokers(); - verifyPeerBrokerInfo(brokers.get("A"), 1); - verifyPeerBrokerInfo(brokers.get("B"), 0); - } - - public void testPeerBrokerCountHalfPeerTwice() throws Exception { - createBroker("A"); - createBroker("B"); - bridgeBrokers("A", "B"); - bridgeBrokers("A", "B"); - startAllBrokers(); - verifyPeerBrokerInfo(brokers.get("A"), 1); - verifyPeerBrokerInfo(brokers.get("B"), 0); - } - - public void testPeerBrokerCountFullPeer() throws Exception { - createBroker("A"); - createBroker("B"); - bridgeBrokers("A", "B"); - bridgeBrokers("B", "A"); - startAllBrokers(); - verifyPeerBrokerInfo(brokers.get("A"), 1); - verifyPeerBrokerInfo(brokers.get("B"), 1); - } - - public void testPeerBrokerCountFullPeerDuplex() throws Exception { - createBroker("A"); - createBroker("B"); - NetworkConnector nc = bridgeBrokers("A", "B"); - nc.setDuplex(true); - startAllBrokers(); - verifyPeerBrokerInfo(brokers.get("A"), 1); - verifyPeerBrokerInfo(brokers.get("B"), 1); - } - - private void verifyPeerBrokerInfo(BrokerItem brokerItem, final int max) throws Exception { - final BrokerService broker = brokerItem.broker; - final RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("verify infos " + broker.getBrokerName() + ", len: " + regionBroker.getPeerBrokerInfos().length); - return max == regionBroker.getPeerBrokerInfos().length; - } - }, 120 * 1000); - LOG.info("verify infos " + broker.getBrokerName() + ", len: " + regionBroker.getPeerBrokerInfos().length); - for (BrokerInfo info : regionBroker.getPeerBrokerInfos()) { - LOG.info(info.getBrokerName()); - } - assertEquals(broker.getBrokerName(), max, regionBroker.getPeerBrokerInfos().length); - } - - private void verifyPeerBrokerInfos(final int max) throws Exception { - Collection brokerList = brokers.values(); - for (Iterator i = brokerList.iterator(); i.hasNext(); ) { - verifyPeerBrokerInfo(i.next(), max); - } - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - } - - @Override - public void tearDown() throws Exception { - super.tearDown(); - ThreadTracker.result(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NewConsumerCreatesDestinationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NewConsumerCreatesDestinationTest.java deleted file mode 100644 index 5d10561fb0..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NewConsumerCreatesDestinationTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Destination; -import javax.jms.Session; -import java.util.Set; - -import org.apache.activemq.EmbeddedBrokerAndConnectionTestSupport; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * - */ -public class NewConsumerCreatesDestinationTest extends EmbeddedBrokerAndConnectionTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(NewConsumerCreatesDestinationTest.class); - - private ActiveMQQueue wildcard; - - public void testNewConsumerCausesNewDestinationToBeAutoCreated() throws Exception { - - // lets create a wildcard thats kinda like those used by Virtual Topics - String wildcardText = "org.*" + getDestinationString().substring("org.apache".length()); - wildcard = new ActiveMQQueue(wildcardText); - - LOG.info("Using wildcard: " + wildcard); - LOG.info("on destination: " + destination); - - assertDestinationCreated(destination, false); - assertDestinationCreated(wildcard, false); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createConsumer(destination); - - assertDestinationCreated(destination, true); - assertDestinationCreated(wildcard, true); - } - - protected void assertDestinationCreated(Destination destination, boolean expected) throws Exception { - Set answer = broker.getBroker().getDestinations((ActiveMQDestination) destination); - int size = expected ? 1 : 0; - assertEquals("Size of found destinations: " + answer, size, answer.size()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NoDuplicateOnTopicNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NoDuplicateOnTopicNetworkTest.java deleted file mode 100644 index 9148e32ec0..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NoDuplicateOnTopicNetworkTest.java +++ /dev/null @@ -1,375 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.jms.Topic; -import java.net.URI; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import junit.framework.Test; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.CombinationTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.Destination; -import org.apache.activemq.broker.region.RegionBroker; -import org.apache.activemq.broker.region.Subscription; -import org.apache.activemq.broker.region.policy.DispatchPolicy; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.broker.region.policy.PriorityNetworkDispatchPolicy; -import org.apache.activemq.broker.region.policy.SimpleDispatchPolicy; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.util.Wait; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class NoDuplicateOnTopicNetworkTest extends CombinationTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(NoDuplicateOnTopicNetworkTest.class); - - private static final String MULTICAST_DEFAULT = "multicast://default"; - private static final String BROKER_1 = "tcp://localhost:61626"; - private static final String BROKER_2 = "tcp://localhost:61636"; - private static final String BROKER_3 = "tcp://localhost:61646"; - private final static String TOPIC_NAME = "broadcast"; - private static byte BASE_PRIORITY = -20; - private BrokerService broker1; - private BrokerService broker2; - private BrokerService broker3; - - public boolean suppressDuplicateTopicSubs = false; - public DispatchPolicy dispatchPolicy = new SimpleDispatchPolicy(); - public boolean durableSub = false; - AtomicInteger idCounter = new AtomicInteger(0); - - private boolean dynamicOnly = false; - // no duplicates in cyclic network if networkTTL <=1 - // when > 1, subscriptions percolate around resulting in duplicates as there is no - // memory of the original subscription. - // solution for 6.0 using org.apache.activemq.command.ConsumerInfo.getNetworkConsumerIds() - private int ttl = 3; - - @Override - protected void setUp() throws Exception { - super.setUp(); - - broker3 = createAndStartBroker("broker3", BROKER_3); - Thread.sleep(3000); - broker2 = createAndStartBroker("broker2", BROKER_2); - Thread.sleep(3000); - broker1 = createAndStartBroker("broker1", BROKER_1); - Thread.sleep(1000); - - waitForBridgeFormation(); - } - - public static Test suite() { - return suite(NoDuplicateOnTopicNetworkTest.class); - } - - protected void waitForBridgeFormation() throws Exception { - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return !broker3.getNetworkConnectors().get(0).activeBridges().isEmpty(); - } - }); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return !broker2.getNetworkConnectors().get(0).activeBridges().isEmpty(); - } - }); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return !broker1.getNetworkConnectors().get(0).activeBridges().isEmpty(); - } - }); - } - - private BrokerService createAndStartBroker(String name, String addr) throws Exception { - BrokerService broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(true); - broker.setBrokerName(name); - broker.addConnector(addr).setDiscoveryUri(new URI(MULTICAST_DEFAULT)); - broker.setUseJmx(false); - - NetworkConnector networkConnector = broker.addNetworkConnector(MULTICAST_DEFAULT); - networkConnector.setDecreaseNetworkConsumerPriority(true); - networkConnector.setDynamicOnly(dynamicOnly); - networkConnector.setNetworkTTL(ttl); - networkConnector.setSuppressDuplicateTopicSubscriptions(suppressDuplicateTopicSubs); - networkConnector.setConsumerPriorityBase(BASE_PRIORITY); - networkConnector.addStaticallyIncludedDestination(new ActiveMQTopic("BeStaticallyIncluded")); - - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policy = new PolicyEntry(); - policy.setDispatchPolicy(dispatchPolicy); - // the audit will suppress the duplicates as it defaults to true so this test - // checking for dups will fail. it is good to have it on in practice. - policy.setEnableAudit(false); - policyMap.put(new ActiveMQTopic(TOPIC_NAME), policy); - broker.setDestinationPolicy(policyMap); - broker.start(); - - return broker; - } - - @Override - protected void tearDown() throws Exception { - broker1.stop(); - broker2.stop(); - broker3.stop(); - super.tearDown(); - } - - public void initCombosForTestProducerConsumerTopic() { - this.addCombinationValues("suppressDuplicateTopicSubs", new Object[]{Boolean.TRUE, Boolean.FALSE}); - this.addCombinationValues("dispatchPolicy", new Object[]{new PriorityNetworkDispatchPolicy(), new SimpleDispatchPolicy()}); - this.addCombinationValues("durableSub", new Object[]{Boolean.TRUE, Boolean.FALSE}); - } - - public void testProducerConsumerTopic() throws Exception { - - final CountDownLatch consumerStarted = new CountDownLatch(1); - - Thread producerThread = new Thread(new Runnable() { - @Override - public void run() { - TopicWithDuplicateMessages producer = new TopicWithDuplicateMessages(); - producer.setBrokerURL(BROKER_1); - producer.setTopicName(TOPIC_NAME); - try { - producer.produce(); - } catch (JMSException e) { - fail("Unexpected " + e); - } - } - }); - - final TopicWithDuplicateMessages consumer = new TopicWithDuplicateMessages(); - Thread consumerThread = new Thread(new Runnable() { - @Override - public void run() { - consumer.setBrokerURL(BROKER_2); - consumer.setTopicName(TOPIC_NAME); - try { - consumer.consumer(); - consumerStarted.countDown(); - consumer.getLatch().await(60, TimeUnit.SECONDS); - } catch (Exception e) { - fail("Unexpected " + e); - } - } - }); - - consumerThread.start(); - LOG.info("Started Consumer"); - - assertTrue("consumer started eventually", consumerStarted.await(10, TimeUnit.SECONDS)); - - // ensure subscription has percolated though the network - Thread.sleep(2000); - - // verify network consumer priority - final RegionBroker regionBroker = (RegionBroker) broker1.getRegionBroker(); - assertTrue("Found network destination with priority as expected", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Map destinationMap = regionBroker.getTopicRegion().getDestinationMap(); - LOG.info("destinations: " + destinationMap.keySet()); - boolean found = false; - for (Destination destination : destinationMap.values()) { - List subscriptions = destination.getConsumers(); - LOG.info(destination + " subscriptions: " + subscriptions); - for (Subscription subscription : subscriptions) { - if (subscription.getConsumerInfo().isNetworkSubscription()) { - LOG.info("subscription: " + subscription + ", priority: " + subscription.getConsumerInfo().getPriority()); - assertTrue("priority is < our base: " + subscription.getConsumerInfo().getPriority(), subscription.getConsumerInfo().getPriority() <= BASE_PRIORITY); - found = true; - } - } - } - return found; - } - })); - - producerThread.start(); - LOG.info("Started Producer"); - producerThread.join(); - consumerThread.join(); - - int duplicateCount = 0; - Map map = new HashMap<>(); - for (String msg : consumer.getMessageStrings()) { - if (map.containsKey(msg)) { - LOG.info("got duplicate: " + msg); - duplicateCount++; - } - map.put(msg, msg); - } - consumer.unSubscribe(); - if (suppressDuplicateTopicSubs || dispatchPolicy instanceof PriorityNetworkDispatchPolicy) { - assertEquals("no duplicates", 0, duplicateCount); - assertEquals("got all required messages: " + map.size(), consumer.getNumMessages(), map.size()); - } else { - assertTrue("we can get some duplicates: " + duplicateCount, duplicateCount >= 0); - if (duplicateCount == 0) { - assertEquals("got all required messages: " + map.size(), consumer.getNumMessages(), map.size()); - } - } - } - - class TopicWithDuplicateMessages { - - private String brokerURL; - private String topicName; - private Connection connection; - private Session session; - private Topic topic; - private MessageProducer producer; - private MessageConsumer consumer; - private final String durableID = "DURABLE_ID"; - - private final List receivedStrings = Collections.synchronizedList(new ArrayList()); - private int numMessages = 10; - private CountDownLatch receivedLatch = new CountDownLatch(numMessages); - - public CountDownLatch getLatch() { - return receivedLatch; - } - - public List getMessageStrings() { - synchronized (receivedStrings) { - return new ArrayList<>(receivedStrings); - } - } - - public String getBrokerURL() { - return brokerURL; - } - - public void setBrokerURL(String brokerURL) { - this.brokerURL = brokerURL; - } - - public String getTopicName() { - return topicName; - } - - public void setTopicName(String topicName) { - this.topicName = topicName; - } - - private void createConnection() throws JMSException { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL); - connection = factory.createConnection(); - connection.setClientID("ID" + idCounter.incrementAndGet()); - } - - private void createTopic() throws JMSException { - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - topic = session.createTopic(topicName); - } - - private void createProducer() throws JMSException { - producer = session.createProducer(topic); - } - - private void createConsumer() throws JMSException { - if (durableSub) { - consumer = session.createDurableSubscriber(topic, durableID); - } else { - consumer = session.createConsumer(topic); - } - consumer.setMessageListener(new MessageListener() { - - @Override - public void onMessage(Message arg0) { - TextMessage msg = (TextMessage) arg0; - try { - LOG.debug("Received message [" + msg.getText() + "]"); - receivedStrings.add(msg.getText()); - receivedLatch.countDown(); - } catch (JMSException e) { - fail("Unexpected :" + e); - } - } - - }); - } - - private void publish() throws JMSException { - for (int i = 0; i < numMessages; i++) { - TextMessage textMessage = session.createTextMessage(); - String message = "message: " + i; - LOG.debug("Sending message[" + message + "]"); - textMessage.setText(message); - producer.send(textMessage); - } - } - - public void produce() throws JMSException { - createConnection(); - createTopic(); - createProducer(); - connection.start(); - publish(); - } - - public void consumer() throws JMSException { - createConnection(); - createTopic(); - createConsumer(); - connection.start(); - } - - public int getNumMessages() { - return numMessages; - } - - public void unSubscribe() throws Exception { - consumer.close(); - if (durableSub) { - session.unsubscribe(durableID); - // ensure un-subscription has percolated though the network - Thread.sleep(2000); - } - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NonBlockingConsumerRedeliveryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NonBlockingConsumerRedeliveryTest.java deleted file mode 100644 index cfae4a2006..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/NonBlockingConsumerRedeliveryTest.java +++ /dev/null @@ -1,441 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.RedeliveryPolicy; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.util.Wait; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class NonBlockingConsumerRedeliveryTest { - - private static final Logger LOG = LoggerFactory.getLogger(NonBlockingConsumerRedeliveryTest.class); - - private final String destinationName = "Destination"; - private final int MSG_COUNT = 100; - - private BrokerService broker; - private String connectionUri; - - private ActiveMQConnectionFactory connectionFactory; - - @Test - public void testMessageDeleiveredWhenNonBlockingEnabled() throws Exception { - - final LinkedHashSet received = new LinkedHashSet<>(); - final LinkedHashSet beforeRollback = new LinkedHashSet<>(); - final LinkedHashSet afterRollback = new LinkedHashSet<>(); - - Connection connection = connectionFactory.createConnection(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(destinationName); - MessageConsumer consumer = session.createConsumer(destination); - - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - received.add(message); - } - }); - - sendMessages(); - - session.commit(); - connection.start(); - - assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + received.size() + " messages."); - return received.size() == MSG_COUNT; - } - })); - - beforeRollback.addAll(received); - received.clear(); - session.rollback(); - - assertTrue("Post-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + received.size() + " messages since rollback."); - return received.size() == MSG_COUNT; - } - })); - - afterRollback.addAll(received); - received.clear(); - - assertEquals(beforeRollback.size(), afterRollback.size()); - assertEquals(beforeRollback, afterRollback); - session.commit(); - } - - @Test - public void testMessageDeleiveredInCorrectOrder() throws Exception { - - final LinkedHashSet received = new LinkedHashSet<>(); - final LinkedHashSet beforeRollback = new LinkedHashSet<>(); - final LinkedHashSet afterRollback = new LinkedHashSet<>(); - - Connection connection = connectionFactory.createConnection(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(destinationName); - MessageConsumer consumer = session.createConsumer(destination); - - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - received.add(message); - } - }); - - sendMessages(); - - session.commit(); - connection.start(); - - assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + received.size() + " messages."); - return received.size() == MSG_COUNT; - } - })); - - beforeRollback.addAll(received); - received.clear(); - session.rollback(); - - assertTrue("Post-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + received.size() + " messages since rollback."); - return received.size() == MSG_COUNT; - } - })); - - afterRollback.addAll(received); - received.clear(); - - assertEquals(beforeRollback.size(), afterRollback.size()); - assertEquals(beforeRollback, afterRollback); - - Iterator after = afterRollback.iterator(); - Iterator before = beforeRollback.iterator(); - - while (before.hasNext() && after.hasNext()) { - TextMessage original = (TextMessage) before.next(); - TextMessage rolledBack = (TextMessage) after.next(); - - int originalInt = Integer.parseInt(original.getText()); - int rolledbackInt = Integer.parseInt(rolledBack.getText()); - - assertEquals(originalInt, rolledbackInt); - } - - session.commit(); - } - - @Test - public void testMessageDeleiveryDoesntStop() throws Exception { - - final LinkedHashSet received = new LinkedHashSet<>(); - final LinkedHashSet beforeRollback = new LinkedHashSet<>(); - final LinkedHashSet afterRollback = new LinkedHashSet<>(); - - Connection connection = connectionFactory.createConnection(); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(destinationName); - MessageConsumer consumer = session.createConsumer(destination); - - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - received.add(message); - } - }); - - sendMessages(); - connection.start(); - - assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + received.size() + " messages."); - return received.size() == MSG_COUNT; - } - })); - - beforeRollback.addAll(received); - received.clear(); - session.rollback(); - - sendMessages(); - - assertTrue("Post-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + received.size() + " messages since rollback."); - return received.size() == MSG_COUNT * 2; - } - })); - - afterRollback.addAll(received); - received.clear(); - - assertEquals(beforeRollback.size() * 2, afterRollback.size()); - - session.commit(); - } - - @Test - public void testNonBlockingMessageDeleiveryIsDelayed() throws Exception { - final LinkedHashSet received = new LinkedHashSet<>(); - - ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.getRedeliveryPolicy().setInitialRedeliveryDelay(TimeUnit.SECONDS.toMillis(6)); - Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(destinationName); - MessageConsumer consumer = session.createConsumer(destination); - - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - received.add(message); - } - }); - - sendMessages(); - connection.start(); - - assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + received.size() + " messages."); - return received.size() == MSG_COUNT; - } - })); - - received.clear(); - session.rollback(); - - assertFalse("Delayed redelivery test not expecting any messages yet.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return received.size() > 0; - } - }, TimeUnit.SECONDS.toMillis(4))); - - session.commit(); - session.close(); - } - - @Test - public void testNonBlockingMessageDeleiveryWithRollbacks() throws Exception { - final LinkedHashSet received = new LinkedHashSet<>(); - - ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); - final Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - final Destination destination = session.createQueue(destinationName); - final MessageConsumer consumer = session.createConsumer(destination); - - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - received.add(message); - } - }); - - sendMessages(); - connection.start(); - - assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + received.size() + " messages."); - return received.size() == MSG_COUNT; - } - })); - - received.clear(); - - consumer.setMessageListener(new MessageListener() { - - int count = 0; - - @Override - public void onMessage(Message message) { - - if (++count > 10) { - try { - session.rollback(); - LOG.info("Rolling back session."); - count = 0; - } catch (JMSException e) { - LOG.warn("Caught an unexpected exception: " + e.getMessage()); - } - } else { - received.add(message); - try { - session.commit(); - } catch (JMSException e) { - LOG.warn("Caught an unexpected exception: " + e.getMessage()); - } - } - } - }); - - session.rollback(); - - assertTrue("Post-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + received.size() + " messages since rollback."); - return received.size() == MSG_COUNT; - } - })); - - assertEquals(MSG_COUNT, received.size()); - session.commit(); - } - - @Test - public void testNonBlockingMessageDeleiveryWithAllRolledBack() throws Exception { - final LinkedHashSet received = new LinkedHashSet<>(); - final LinkedHashSet dlqed = new LinkedHashSet<>(); - - ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection(); - connection.getRedeliveryPolicy().setMaximumRedeliveries(5); - final Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - final Destination destination = session.createQueue(destinationName); - final Destination dlq = session.createQueue("ActiveMQ.DLQ"); - final MessageConsumer consumer = session.createConsumer(destination); - final MessageConsumer dlqConsumer = session.createConsumer(dlq); - - dlqConsumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - dlqed.add(message); - } - }); - - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - received.add(message); - } - }); - - sendMessages(); - connection.start(); - - assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + received.size() + " messages."); - return received.size() == MSG_COUNT; - } - })); - - session.rollback(); - - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - try { - session.rollback(); - } catch (JMSException e) { - LOG.warn("Caught an unexpected exception: " + e.getMessage()); - } - } - }); - - assertTrue("Post-Rollback expects to DLQ: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Consumer has received " + dlqed.size() + " messages in DLQ."); - return dlqed.size() == MSG_COUNT; - } - })); - - session.commit(); - } - - private void sendMessages() throws Exception { - Connection connection = connectionFactory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue(destinationName); - MessageProducer producer = session.createProducer(destination); - for (int i = 0; i < MSG_COUNT; ++i) { - producer.send(session.createTextMessage("" + i)); - } - } - - @Before - public void startBroker() throws Exception { - broker = new BrokerService(); - broker.setDeleteAllMessagesOnStartup(true); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://0.0.0.0:0"); - broker.start(); - broker.waitUntilStarted(); - - connectionUri = broker.getTransportConnectors().get(0).getPublishableConnectString(); - connectionFactory = new ActiveMQConnectionFactory(connectionUri); - connectionFactory.setNonBlockingRedelivery(true); - - RedeliveryPolicy policy = connectionFactory.getRedeliveryPolicy(); - policy.setInitialRedeliveryDelay(TimeUnit.SECONDS.toMillis(2)); - policy.setBackOffMultiplier(-1); - policy.setRedeliveryDelay(TimeUnit.SECONDS.toMillis(2)); - policy.setMaximumRedeliveryDelay(-1); - policy.setUseExponentialBackOff(false); - policy.setMaximumRedeliveries(-1); - } - - @After - public void stopBroker() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ObjectMessageNotSerializableTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ObjectMessageNotSerializableTest.java deleted file mode 100644 index bbaa266113..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ObjectMessageNotSerializableTest.java +++ /dev/null @@ -1,277 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.util.Vector; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import junit.framework.Test; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.CombinationTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQObjectMessage; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ObjectMessageNotSerializableTest extends CombinationTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(ObjectMessageNotSerializableTest.class); - - BrokerService broker; - AtomicInteger numReceived = new AtomicInteger(0); - final Vector exceptions = new Vector<>(); - - public static Test suite() { - return suite(ObjectMessageNotSerializableTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - @Override - protected void setUp() throws Exception { - exceptions.clear(); - broker = createBroker(); - } - - public void testSendNotSerializeableObjectMessage() throws Exception { - - final ActiveMQDestination destination = new ActiveMQQueue("testQ"); - final MyObject obj = new MyObject("A message"); - - final CountDownLatch consumerStarted = new CountDownLatch(1); - - Thread vmConsumerThread = new Thread("Consumer Thread") { - @Override - public void run() { - try { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - factory.setOptimizedMessageDispatch(true); - factory.setObjectMessageSerializationDefered(true); - factory.setCopyMessageOnSend(false); - - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - connection.start(); - consumerStarted.countDown(); - ActiveMQObjectMessage message = (ActiveMQObjectMessage) consumer.receive(30000); - if (message != null) { - MyObject object = (MyObject) message.getObject(); - LOG.info("Got message " + object.getMessage()); - numReceived.incrementAndGet(); - } - consumer.close(); - } catch (Throwable ex) { - exceptions.add(ex); - } - } - }; - vmConsumerThread.start(); - - Thread producingThread = new Thread("Producing Thread") { - @Override - public void run() { - try { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - factory.setOptimizedMessageDispatch(true); - factory.setObjectMessageSerializationDefered(true); - factory.setCopyMessageOnSend(false); - - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - ActiveMQObjectMessage message = (ActiveMQObjectMessage) session.createObjectMessage(); - message.setObject(obj); - producer.send(message); - producer.close(); - } catch (Throwable ex) { - exceptions.add(ex); - } - } - }; - - assertTrue("consumers started", consumerStarted.await(10, TimeUnit.SECONDS)); - producingThread.start(); - - vmConsumerThread.join(); - producingThread.join(); - - assertEquals("writeObject called", 0, obj.getWriteObjectCalled()); - assertEquals("readObject called", 0, obj.getReadObjectCalled()); - assertEquals("readObjectNoData called", 0, obj.getReadObjectNoDataCalled()); - - assertEquals("Got expected messages", 1, numReceived.get()); - assertTrue("no unexpected exceptions: " + exceptions, exceptions.isEmpty()); - } - - public void testSendNotSerializeableObjectMessageOverTcp() throws Exception { - final ActiveMQDestination destination = new ActiveMQTopic("testTopic"); - final MyObject obj = new MyObject("A message"); - - final CountDownLatch consumerStarted = new CountDownLatch(3); - final Vector exceptions = new Vector<>(); - Thread vmConsumerThread = new Thread("Consumer Thread") { - @Override - public void run() { - try { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - factory.setOptimizedMessageDispatch(true); - factory.setObjectMessageSerializationDefered(true); - factory.setCopyMessageOnSend(false); - - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - connection.start(); - consumerStarted.countDown(); - ActiveMQObjectMessage message = (ActiveMQObjectMessage) consumer.receive(30000); - if (message != null) { - MyObject object = (MyObject) message.getObject(); - LOG.info("Got message " + object.getMessage()); - numReceived.incrementAndGet(); - } - consumer.close(); - } catch (Throwable ex) { - exceptions.add(ex); - } - } - }; - vmConsumerThread.start(); - - Thread tcpConsumerThread = new Thread("Consumer Thread") { - @Override - public void run() { - try { - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri()); - factory.setOptimizedMessageDispatch(true); - - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - connection.start(); - consumerStarted.countDown(); - ActiveMQObjectMessage message = (ActiveMQObjectMessage) consumer.receive(30000); - if (message != null) { - MyObject object = (MyObject) message.getObject(); - LOG.info("Got message " + object.getMessage()); - numReceived.incrementAndGet(); - assertEquals("readObject called", 1, object.getReadObjectCalled()); - } - consumer.close(); - } catch (Throwable ex) { - exceptions.add(ex); - } - } - }; - tcpConsumerThread.start(); - - Thread notherVmConsumerThread = new Thread("Consumer Thread") { - @Override - public void run() { - try { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - factory.setOptimizedMessageDispatch(true); - factory.setObjectMessageSerializationDefered(true); - factory.setCopyMessageOnSend(false); - - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = session.createConsumer(destination); - connection.start(); - consumerStarted.countDown(); - ActiveMQObjectMessage message = (ActiveMQObjectMessage) consumer.receive(30000); - if (message != null) { - MyObject object = (MyObject) message.getObject(); - LOG.info("Got message " + object.getMessage()); - numReceived.incrementAndGet(); - } - consumer.close(); - } catch (Throwable ex) { - exceptions.add(ex); - } - } - }; - notherVmConsumerThread.start(); - - Thread producingThread = new Thread("Producing Thread") { - @Override - public void run() { - try { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - factory.setOptimizedMessageDispatch(true); - factory.setObjectMessageSerializationDefered(true); - factory.setCopyMessageOnSend(false); - - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(destination); - ActiveMQObjectMessage message = (ActiveMQObjectMessage) session.createObjectMessage(); - message.setObject(obj); - producer.send(message); - producer.close(); - } catch (Throwable ex) { - exceptions.add(ex); - } - } - }; - - assertTrue("consumers started", consumerStarted.await(10, TimeUnit.SECONDS)); - producingThread.start(); - - vmConsumerThread.join(); - tcpConsumerThread.join(); - notherVmConsumerThread.join(); - producingThread.join(); - - assertEquals("writeObject called", 1, obj.getWriteObjectCalled()); - assertEquals("readObject called", 0, obj.getReadObjectCalled()); - assertEquals("readObjectNoData called", 0, obj.getReadObjectNoDataCalled()); - - assertEquals("Got expected messages", 3, numReceived.get()); - assertTrue("no unexpected exceptions: " + exceptions, exceptions.isEmpty()); - } - - private BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.addConnector("tcp://localhost:0"); - - broker.start(); - broker.waitUntilStarted(); - return broker; - } - - @Override - protected void tearDown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ProducerConsumerTestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ProducerConsumerTestSupport.java deleted file mode 100644 index b9b87e6a0e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ProducerConsumerTestSupport.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.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; - -/** - * Base class for simple test cases using a single connection, session - * producer and consumer - */ -public class ProducerConsumerTestSupport extends TestSupport { - - protected Connection connection; - protected Session session; - protected MessageProducer producer; - protected MessageConsumer consumer; - protected Destination destination; - - @Override - protected void setUp() throws Exception { - super.setUp(); - connection = createConnection(); - session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - destination = this.createDestination(getSubject()); - producer = session.createProducer(destination); - consumer = session.createConsumer(destination); - connection.start(); - } - - @Override - protected void tearDown() throws Exception { - consumer.close(); - producer.close(); - session.close(); - connection.close(); - super.tearDown(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnDurableTopicConsumedMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnDurableTopicConsumedMessageTest.java deleted file mode 100644 index 6d0564900a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnDurableTopicConsumedMessageTest.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.activemq.usecases; - -/** - * - */ -public class PublishOnDurableTopicConsumedMessageTest extends PublishOnTopicConsumedMessageTest { - - @Override - protected void setUp() throws Exception { - this.durable = true; - super.setUp(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageInTransactionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageInTransactionTest.java deleted file mode 100644 index a6a3a9a7c7..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageInTransactionTest.java +++ /dev/null @@ -1,189 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.ObjectMessage; -import javax.jms.Session; -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.util.IOHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public final class PublishOnQueueConsumedMessageInTransactionTest extends TestCase implements MessageListener { - - private static final Logger LOG = LoggerFactory.getLogger(PublishOnQueueConsumedMessageInTransactionTest.class); - - private Session producerSession; - private Session consumerSession; - private Destination queue; - private ActiveMQConnectionFactory factory; - private MessageProducer producer; - private MessageConsumer consumer; - private Connection connection; - private ObjectMessage objectMessage; - private List messages = createConcurrentList(); - private final Object lock = new Object(); - private String[] data; - private String dataFileRoot = IOHelper.getDefaultDataDirectory(); - private int messageCount = 3; - private String url = "vm://localhost"; - - // Invalid acknowledgment warning can be viewed on the console of a remote - // broker - // The warning message is not thrown back to the client - // private String url = "tcp://localhost:61616"; - - @Override - protected void setUp() throws Exception { - File dataFile = new File(dataFileRoot); - recursiveDelete(dataFile); - try { - factory = new ActiveMQConnectionFactory(url); - connection = factory.createConnection(); - producerSession = connection.createSession(true, Session.SESSION_TRANSACTED); - consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED); - queue = new ActiveMQQueue("FOO.BAR"); - data = new String[messageCount]; - - for (int i = 0; i < messageCount; i++) { - data[i] = "Message : " + i; - } - } catch (JMSException je) { - fail("Error setting up connection : " + je.toString()); - } - } - - public void testSendReceive() throws Exception { - sendMessage(); - - connection.start(); - consumer = consumerSession.createConsumer(queue); - consumer.setMessageListener(this); - waitForMessagesToBeDelivered(); - assertEquals("Messages received doesn't equal messages sent", messages.size(), data.length); - - } - - protected void sendMessage() throws JMSException { - messages.clear(); - try { - for (int i = 0; i < data.length; ++i) { - producer = producerSession.createProducer(queue); - objectMessage = producerSession.createObjectMessage(data[i]); - producer.send(objectMessage); - producerSession.commit(); - LOG.info("sending message :" + objectMessage); - } - } catch (Exception e) { - if (producerSession != null) { - producerSession.rollback(); - LOG.info("rollback"); - producerSession.close(); - } - - e.printStackTrace(); - } - } - - @Override - public synchronized void onMessage(Message m) { - try { - objectMessage = (ObjectMessage) m; - consumeMessage(objectMessage, messages); - - LOG.info("consumer received message :" + objectMessage); - consumerSession.commit(); - - } catch (Exception e) { - try { - consumerSession.rollback(); - LOG.info("rolled back transaction"); - } catch (JMSException e1) { - LOG.info(e1.toString()); - e1.printStackTrace(); - } - LOG.info(e.toString()); - e.printStackTrace(); - } - } - - protected void consumeMessage(Message message, List messageList) { - messageList.add(message); - if (messageList.size() >= data.length) { - synchronized (lock) { - lock.notifyAll(); - } - } - - } - - protected List createConcurrentList() { - return Collections.synchronizedList(new ArrayList()); - } - - protected void waitForMessagesToBeDelivered() { - long maxWaitTime = 5000; - long waitTime = maxWaitTime; - long start = (maxWaitTime <= 0) ? 0 : System.currentTimeMillis(); - - synchronized (lock) { - while (messages.size() <= data.length && waitTime >= 0) { - try { - lock.wait(200); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - waitTime = maxWaitTime - (System.currentTimeMillis() - start); - } - } - } - - protected static void recursiveDelete(File file) { - if (file.isDirectory()) { - File[] files = file.listFiles(); - for (int i = 0; i < files.length; i++) { - recursiveDelete(files[i]); - } - } - file.delete(); - } - - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - - super.tearDown(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageTest.java deleted file mode 100644 index 1ed804ad47..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageTest.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.activemq.usecases; - -/** - * - */ -public class PublishOnQueueConsumedMessageTest extends PublishOnTopicConsumedMessageTest { - - @Override - protected void setUp() throws Exception { - topic = false; - super.setUp(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageUsingActivemqXMLTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageUsingActivemqXMLTest.java deleted file mode 100644 index e6d88aca8e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnQueueConsumedMessageUsingActivemqXMLTest.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.activemq.usecases; - -import java.io.File; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.xbean.BrokerFactoryBean; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; - -/** - * Test Publish/Consume queue using the release activemq.xml configuration file - */ -public class PublishOnQueueConsumedMessageUsingActivemqXMLTest extends PublishOnTopicConsumedMessageTest { - - protected static final String JOURNAL_ROOT = "../data/"; - private static final transient Logger LOG = LoggerFactory.getLogger(PublishOnQueueConsumedMessageUsingActivemqXMLTest.class); - BrokerService broker; - - /** - * Use the transportConnector uri configured on the activemq.xml - * - * @return ActiveMQConnectionFactory - * @throws Exception - */ - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("tcp://localhost:61616"); - } - - /** - * Sets up a test where the producer and consumer have their own connection. - * - * @see junit.framework.TestCase#setUp() - */ - @Override - protected void setUp() throws Exception { - File journalFile = new File(JOURNAL_ROOT); - recursiveDelete(journalFile); - // Create broker from resource - LOG.info("Creating broker... "); - broker = createBroker("org/apache/activemq/usecases/activemq.xml"); - LOG.info("Success"); - super.setUp(); - } - - /* - * Stops the Broker - * @see junit.framework.TestCase#tearDown() - */ - @Override - protected void tearDown() throws Exception { - LOG.info("Closing Broker"); - if (broker != null) { - broker.stop(); - } - LOG.info("Broker closed..."); - } - - protected BrokerService createBroker(String resource) throws Exception { - return createBroker(new ClassPathResource(resource)); - } - - protected BrokerService createBroker(Resource resource) throws Exception { - BrokerFactoryBean factory = new BrokerFactoryBean(resource); - factory.afterPropertiesSet(); - - BrokerService broker = factory.getBroker(); - - //assertTrue("Should have a broker!", broker != null); - - return broker; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTemporaryQueueConsumedMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTemporaryQueueConsumedMessageTest.java deleted file mode 100644 index c40d119607..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTemporaryQueueConsumedMessageTest.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.activemq.usecases; - -import javax.jms.DeliveryMode; - -/** - * - */ -public class PublishOnTemporaryQueueConsumedMessageTest extends PublishOnTopicConsumedMessageTest { - - @Override - protected void setUp() throws Exception { - topic = false; - deliveryMode = DeliveryMode.NON_PERSISTENT; - super.setUp(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTopicConsumedMessageTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTopicConsumedMessageTest.java deleted file mode 100644 index d0a6dcc5a1..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTopicConsumedMessageTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageProducer; - -import org.apache.activemq.test.JmsTopicSendReceiveWithTwoConnectionsTest; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class PublishOnTopicConsumedMessageTest extends JmsTopicSendReceiveWithTwoConnectionsTest { - - private static final Logger LOG = LoggerFactory.getLogger(PublishOnTopicConsumedMessageTest.class); - - private MessageProducer replyProducer; - - @Override - public synchronized void onMessage(Message message) { - - // lets resend the message somewhere else - try { - Message msgCopy = (Message) ((org.apache.activemq.command.Message) message).copy(); - replyProducer.send(msgCopy); - - // log.info("Sending reply: " + message); - super.onMessage(message); - } catch (JMSException e) { - LOG.info("Failed to send message: " + e); - e.printStackTrace(); - } - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - - Destination replyDestination = null; - - if (topic) { - replyDestination = receiveSession.createTopic("REPLY." + getSubject()); - } else { - replyDestination = receiveSession.createQueue("REPLY." + getSubject()); - } - - replyProducer = receiveSession.createProducer(replyDestination); - LOG.info("Created replyProducer: " + replyProducer); - - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTopicConsumerMessageUsingActivemqXMLTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTopicConsumerMessageUsingActivemqXMLTest.java deleted file mode 100644 index 1e215d53ce..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/PublishOnTopicConsumerMessageUsingActivemqXMLTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import java.io.File; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.xbean.BrokerFactoryBean; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; - -/** - * Test Publish/Consume topic using the release activemq.xml configuration file - */ -public class PublishOnTopicConsumerMessageUsingActivemqXMLTest extends PublishOnTopicConsumedMessageTest { - - protected static final String JOURNAL_ROOT = "../data/"; - private static final transient Logger LOG = LoggerFactory.getLogger(PublishOnTopicConsumerMessageUsingActivemqXMLTest.class); - - BrokerService broker; - - /** - * Use the transportConnector uri configured on the activemq.xml - * - * @return ActiveMQConnectionFactory - * @throws Exception - */ - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("tcp://localhost:61616"); - } - - /** - * Sets up a test where the producer and consumer have their own connection. - * - * @see junit.framework.TestCase#setUp() - */ - @Override - protected void setUp() throws Exception { - File journalFile = new File(JOURNAL_ROOT); - recursiveDelete(journalFile); - // Create broker from resource - LOG.info("Creating broker... "); - broker = createBroker("org/apache/activemq/usecases/activemq.xml"); - LOG.info("Success"); - super.setUp(); - } - - /* - * Stops the Broker - * @see junit.framework.TestCase#tearDown() - */ - @Override - protected void tearDown() throws Exception { - LOG.info("Closing Broker"); - if (broker != null) { - broker.stop(); - } - LOG.info("Broker closed..."); - } - - protected BrokerService createBroker(String resource) throws Exception { - return createBroker(new ClassPathResource(resource)); - } - - protected BrokerService createBroker(Resource resource) throws Exception { - BrokerFactoryBean factory = new BrokerFactoryBean(resource); - factory.afterPropertiesSet(); - - BrokerService broker = factory.getBroker(); - - //assertTrue("Should have a broker!", broker != null); - - return broker; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingLevelDBTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingLevelDBTest.java deleted file mode 100644 index 1ae74c3b7f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingLevelDBTest.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.activemq.usecases; - -import java.io.File; -import java.io.IOException; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.leveldb.LevelDBStore; - -public class QueueBrowsingLevelDBTest extends QueueBrowsingTest { - - @Override - public BrokerService createBroker() throws IOException { - BrokerService broker = super.createBroker(); - LevelDBStore store = new LevelDBStore(); - store.setDirectory(new File("target/test-data/leveldb")); - broker.setPersistenceAdapter(store); - return broker; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingLimitTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingLimitTest.java deleted file mode 100644 index 86c3857f5c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingLimitTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageProducer; -import javax.jms.QueueBrowser; -import javax.jms.Session; -import java.io.IOException; -import java.net.URI; -import java.util.Enumeration; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQQueue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; - -public class QueueBrowsingLimitTest { - - private static final Logger LOG = LoggerFactory.getLogger(QueueBrowsingLimitTest.class); - - private BrokerService broker; - private URI connectUri; - private ActiveMQConnectionFactory factory; - private final int browserLimit = 300; - - @Before - public void startBroker() throws Exception { - broker = createBroker(); - TransportConnector connector = broker.addConnector("tcp://0.0.0.0:0"); - broker.deleteAllMessages(); - broker.start(); - broker.waitUntilStarted(); - - PolicyEntry policy = new PolicyEntry(); - policy.setMaxBrowsePageSize(browserLimit); - broker.setDestinationPolicy(new PolicyMap()); - broker.getDestinationPolicy().setDefaultEntry(policy); - - connectUri = connector.getConnectUri(); - factory = new ActiveMQConnectionFactory(connectUri); - - } - - public BrokerService createBroker() throws IOException { - return new BrokerService(); - } - - @After - public void stopBroker() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } - - @Test - public void testBrowsingLimited() throws Exception { - - int messageToSend = 470; - - ActiveMQQueue queue = new ActiveMQQueue("TEST"); - Connection connection = factory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(queue); - - String data = ""; - for (int i = 0; i < 1024 * 2; i++) { - data += "x"; - } - - for (int i = 0; i < messageToSend; i++) { - producer.send(session.createTextMessage(data)); - } - - QueueBrowser browser = session.createBrowser(queue); - Enumeration enumeration = browser.getEnumeration(); - int received = 0; - while (enumeration.hasMoreElements()) { - Message m = (Message) enumeration.nextElement(); - received++; - LOG.info("Browsed message " + received + ": " + m.getJMSMessageID()); - } - - browser.close(); - - assertEquals(browserLimit, received); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingTest.java deleted file mode 100644 index 2630b73786..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueBrowsingTest.java +++ /dev/null @@ -1,214 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.QueueBrowser; -import javax.jms.Session; -import java.io.IOException; -import java.net.URI; -import java.util.Enumeration; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQQueue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class QueueBrowsingTest { - - private static final Logger LOG = LoggerFactory.getLogger(QueueBrowsingTest.class); - - private BrokerService broker; - private URI connectUri; - private ActiveMQConnectionFactory factory; - private final int maxPageSize = 100; - - @Before - public void startBroker() throws Exception { - broker = createBroker(); - TransportConnector connector = broker.addConnector("tcp://0.0.0.0:0"); - broker.deleteAllMessages(); - broker.start(); - broker.waitUntilStarted(); - - PolicyEntry policy = new PolicyEntry(); - policy.setMaxPageSize(maxPageSize); - broker.setDestinationPolicy(new PolicyMap()); - broker.getDestinationPolicy().setDefaultEntry(policy); - - connectUri = connector.getConnectUri(); - factory = new ActiveMQConnectionFactory(connectUri); - } - - public BrokerService createBroker() throws IOException { - return new BrokerService(); - } - - @After - public void stopBroker() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } - - @Test - public void testBrowsing() throws JMSException { - - int messageToSend = 370; - - ActiveMQQueue queue = new ActiveMQQueue("TEST"); - Connection connection = factory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(queue); - - String data = ""; - for (int i = 0; i < 1024 * 2; i++) { - data += "x"; - } - - for (int i = 0; i < messageToSend; i++) { - producer.send(session.createTextMessage(data)); - } - - QueueBrowser browser = session.createBrowser(queue); - Enumeration enumeration = browser.getEnumeration(); - int received = 0; - while (enumeration.hasMoreElements()) { - Message m = (Message) enumeration.nextElement(); - received++; - LOG.info("Browsed message " + received + ": " + m.getJMSMessageID()); - } - - browser.close(); - - assertEquals(messageToSend, received); - } - - @Test - public void testBrowseConcurrent() throws Exception { - final int messageToSend = 370; - - final ActiveMQQueue queue = new ActiveMQQueue("TEST"); - Connection connection = factory.createConnection(); - connection.start(); - final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageProducer producer = session.createProducer(queue); - - String data = ""; - for (int i = 0; i < 1024 * 2; i++) { - data += "x"; - } - - for (int i = 0; i < messageToSend; i++) { - producer.send(session.createTextMessage(data)); - } - - Thread browserThread = new Thread() { - @Override - public void run() { - try { - QueueBrowser browser = session.createBrowser(queue); - Enumeration enumeration = browser.getEnumeration(); - int received = 0; - while (enumeration.hasMoreElements()) { - Message m = (Message) enumeration.nextElement(); - received++; - LOG.info("Browsed message " + received + ": " + m.getJMSMessageID()); - } - assertEquals("Browsed all messages", messageToSend, received); - } catch (Exception e) { - e.printStackTrace(); - } - } - }; - - browserThread.start(); - - Thread consumerThread = new Thread() { - @Override - public void run() { - try { - MessageConsumer consumer = session.createConsumer(queue); - int received = 0; - while (true) { - Message m = consumer.receive(1000); - if (m == null) - break; - received++; - } - assertEquals("Consumed all messages", messageToSend, received); - } catch (Exception e) { - e.printStackTrace(); - } - } - }; - - consumerThread.start(); - - browserThread.join(); - consumerThread.join(); - } - - @Test - public void testMemoryLimit() throws Exception { - broker.getSystemUsage().getMemoryUsage().setLimit(16 * 1024); - - int messageToSend = 370; - - ActiveMQQueue queue = new ActiveMQQueue("TEST"); - Connection connection = factory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(queue); - - String data = ""; - for (int i = 0; i < 1024 * 2; i++) { - data += "x"; - } - - for (int i = 0; i < messageToSend; i++) { - producer.send(session.createTextMessage(data)); - } - - QueueBrowser browser = session.createBrowser(queue); - Enumeration enumeration = browser.getEnumeration(); - int received = 0; - while (enumeration.hasMoreElements()) { - Message m = (Message) enumeration.nextElement(); - received++; - LOG.info("Browsed message " + received + ": " + m.getJMSMessageID()); - } - - browser.close(); - assertTrue("got at least maxPageSize", received >= maxPageSize); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueConsumerCloseAndReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueConsumerCloseAndReconnectTest.java deleted file mode 100644 index 5d73386cf0..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueConsumerCloseAndReconnectTest.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.activemq.usecases; - -/** - * - */ -public class QueueConsumerCloseAndReconnectTest extends DurableConsumerCloseAndReconnectTest { - - @Override - protected boolean isTopic() { - return false; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueDuplicatesTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueDuplicatesTest.java deleted file mode 100644 index 221c4c1461..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueDuplicatesTest.java +++ /dev/null @@ -1,163 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class QueueDuplicatesTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(QueueDuplicatesTest.class); - - private static DateFormat formatter = new SimpleDateFormat("HH:mm:ss SSS"); - private String brokerUrl; - private String subject; - private Connection brokerConnection; - - public QueueDuplicatesTest(String name) { - super(name); - } - - @Override - protected void setUp() throws Exception { - String peerUrl = "peer://localhost:6099"; - - subject = this.getClass().getName(); - - ActiveMQConnectionFactory fac = createFactory(peerUrl); - brokerConnection = fac.createConnection(); - brokerConnection.start(); - } - - @Override - protected void tearDown() throws Exception { - if (brokerConnection != null) { - brokerConnection.close(); - } - } - - public void testDuplicates() { - try { - // Get Session - Session session = createSession(brokerConnection); - // create consumer - Destination dest = session.createQueue(subject); - MessageConsumer consumer = session.createConsumer(dest); - // subscribe to queue - consumer.setMessageListener(new SimpleConsumer()); - // create producer - Thread sendingThread = new SendingThread(brokerUrl, subject); - // start producer - sendingThread.start(); - // wait about 5 seconds - Thread.sleep(5000); - // unsubscribe consumer - consumer.close(); - // wait another 5 seconds - Thread.sleep(5000); - // create new consumer - consumer = session.createConsumer(dest); - // subscribe to queue - consumer.setMessageListener(new SimpleConsumer()); - // sleep a little while longer - Thread.sleep(15000); - session.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - Session createSession(Connection peerConnection) throws JMSException { - // Connect using peer to peer connection - Session session = peerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - return session; - } - - private ActiveMQConnectionFactory createFactory(String brokerUrl) { - ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(); - cf.setBrokerURL(brokerUrl); - - return cf; - } - - private class SendingThread extends Thread { - - private final String subject; - - SendingThread(String brokerUrl, String subject) { - this.subject = subject; - setDaemon(false); - } - - @Override - public void run() { - try { - Session session = createSession(brokerConnection); - Destination dest = session.createQueue(subject); - MessageProducer producer = session.createProducer(dest); - producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - for (int i = 0; i < 20; i++) { - String txt = "Text Message: " + i; - TextMessage msg = session.createTextMessage(txt); - producer.send(msg); - LOG.info(formatter.format(new Date()) + " Sent ==> " + msg + " to " + subject); - Thread.sleep(1000); - } - session.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - private static class SimpleConsumer implements MessageListener { - - private final Map msgs = new HashMap<>(); - - @Override - public void onMessage(Message message) { - LOG.info(formatter.format(new Date()) + " SimpleConsumer Message Received: " + message); - try { - String id = message.getJMSMessageID(); - assertNull("Message is duplicate: " + id, msgs.get(id)); - msgs.put(id, message); - } catch (Exception e) { - e.printStackTrace(); - } - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueMemoryFullMultiBrokersTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueMemoryFullMultiBrokersTest.java deleted file mode 100644 index 546891a404..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueMemoryFullMultiBrokersTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Destination; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.Queue; -import org.apache.activemq.broker.region.RegionBroker; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.broker.region.policy.VMPendingQueueMessageStoragePolicy; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.usage.SystemUsage; - -public class QueueMemoryFullMultiBrokersTest extends JmsMultipleBrokersTestSupport { - - public static final int BROKER_COUNT = 2; - public static final int MESSAGE_COUNT = 2000; - - public void testQueueNetworkWithConsumerFull() throws Exception { - - bridgeAllBrokers(); - startAllBrokers(); - - Destination dest = createDestination("TEST.FOO", false); - - sendMessages("Broker1", dest, 50); - - CountDownLatch latch = new CountDownLatch(MESSAGE_COUNT); - createConsumer("Broker2", dest, latch); - assertConsumersConnect("Broker1", dest, 1, 30000); - sendMessages("Broker1", dest, MESSAGE_COUNT - 50); - - // Wait for messages to be delivered - assertTrue("Missing " + latch.getCount() + " messages", latch.await(45, TimeUnit.SECONDS)); - - // verify stats, all messages acked - BrokerService broker1 = brokers.get("Broker1").broker; - RegionBroker regionBroker = (RegionBroker) broker1.getRegionBroker(); - // give the acks a chance to flow - Thread.sleep(2000); - Queue internalQueue = (Queue) regionBroker.getDestinations(ActiveMQDestination.transform(dest)).iterator().next(); - - assertTrue("All messages are consumed and acked from source:" + internalQueue, internalQueue.getMessages().isEmpty()); - assertEquals("messages source:" + internalQueue, 0, internalQueue.getDestinationStatistics().getMessages().getCount()); - assertEquals("inflight source:" + internalQueue, 0, internalQueue.getDestinationStatistics().getInflight().getCount()); - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - messageSize = 1024; - - // Setup n brokers - for (int i = 1; i <= BROKER_COUNT; i++) { - createBroker(new URI("broker:()/Broker" + i + "?persistent=false&useJmx=false")); - } - BrokerService broker2 = brokers.get("Broker2").broker; - applyMemoryLimitPolicy(broker2); - } - - private void applyMemoryLimitPolicy(BrokerService broker) { - final SystemUsage memoryManager = new SystemUsage(); - memoryManager.getMemoryUsage().setLimit(1024 * 50); // 50 MB - broker.setSystemUsage(memoryManager); - - final List policyEntries = new ArrayList<>(); - final PolicyEntry entry = new PolicyEntry(); - entry.setQueue(">"); - entry.setMemoryLimit(1024 * 4); // Set to 2 kb - entry.setPendingQueuePolicy(new VMPendingQueueMessageStoragePolicy()); - policyEntries.add(entry); - - final PolicyMap policyMap = new PolicyMap(); - policyMap.setPolicyEntries(policyEntries); - broker.setDestinationPolicy(policyMap); - - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueRedeliverTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueRedeliverTest.java deleted file mode 100644 index e59f554738..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueRedeliverTest.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.activemq.usecases; - -/** - * - */ -public class QueueRedeliverTest extends TopicRedeliverTest { - - @Override - protected void setUp() throws Exception { - super.setUp(); - topic = false; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueRepeaterTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueRepeaterTest.java deleted file mode 100644 index caa21bbb94..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/QueueRepeaterTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.util.Date; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.command.ActiveMQQueue; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author pragmasoft - */ -public final class QueueRepeaterTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(QueueRepeaterTest.class); - - private volatile String receivedText; - - private Session producerSession; - private Session consumerSession; - private Destination queue; - - private MessageProducer producer; - private MessageConsumer consumer; - private Connection connection; - private CountDownLatch latch = new CountDownLatch(1); - - public void testTransaction() throws Exception { - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); - connection = factory.createConnection(); - queue = new ActiveMQQueue(getClass().getName() + "." + getName()); - - producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumerSession = connection.createSession(true, 0); - - producer = producerSession.createProducer(queue); - - consumer = consumerSession.createConsumer(queue); - consumer.setMessageListener(new MessageListener() { - - @Override - public void onMessage(Message m) { - try { - TextMessage tm = (TextMessage) m; - receivedText = tm.getText(); - latch.countDown(); - - LOG.info("consumer received message :" + receivedText); - consumerSession.commit(); - LOG.info("committed transaction"); - } catch (JMSException e) { - try { - consumerSession.rollback(); - LOG.info("rolled back transaction"); - } catch (JMSException e1) { - LOG.info(e1.toString()); - e1.printStackTrace(); - } - LOG.info(e.toString()); - e.printStackTrace(); - } - } - }); - - connection.start(); - - TextMessage tm = null; - try { - tm = producerSession.createTextMessage(); - tm.setText("Hello, " + new Date()); - producer.send(tm); - LOG.info("producer sent message :" + tm.getText()); - } catch (JMSException e) { - e.printStackTrace(); - } - - LOG.info("Waiting for latch"); - latch.await(2, TimeUnit.SECONDS); - assertNotNull(receivedText); - LOG.info("test completed, destination=" + receivedText); - } - - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - super.tearDown(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ReliableReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ReliableReconnectTest.java deleted file mode 100644 index d94651962b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ReliableReconnectTest.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.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.jms.Topic; -import java.net.URI; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.util.IdGenerator; - -public class ReliableReconnectTest extends org.apache.activemq.TestSupport { - - protected static final int MESSAGE_COUNT = 100; - protected static final String DEFAULT_BROKER_URL = ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL; - private static final int RECEIVE_TIMEOUT = 10000; - - protected int deliveryMode = DeliveryMode.PERSISTENT; - protected String consumerClientId; - protected Destination destination; - protected final AtomicBoolean closeBroker = new AtomicBoolean(false); - protected final AtomicInteger messagesReceived = new AtomicInteger(0); - protected BrokerService broker; - protected int firstBatch = MESSAGE_COUNT / 10; - private IdGenerator idGen = new IdGenerator(); - - public ReliableReconnectTest() { - } - - @Override - protected void setUp() throws Exception { - this.setAutoFail(true); - consumerClientId = idGen.generateId(); - super.setUp(); - topic = true; - destination = createDestination(getClass().getName()); - } - - @Override - protected void tearDown() throws Exception { - if (broker != null) { - broker.stop(); - } - } - - @Override - public ActiveMQConnectionFactory getConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory(); - } - - protected void startBroker(boolean deleteOnStart) throws JMSException { - try { - broker = BrokerFactory.createBroker(new URI("broker://()/localhost")); - broker.setUseShutdownHook(false); - broker.setDeleteAllMessagesOnStartup(deleteOnStart); - - broker.setUseJmx(false); - broker.addConnector(DEFAULT_BROKER_URL); - broker.start(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - protected Connection createConsumerConnection() throws Exception { - Connection consumerConnection = getConnectionFactory().createConnection(); - consumerConnection.setClientID(consumerClientId); - consumerConnection.start(); - return consumerConnection; - } - - protected MessageConsumer createConsumer(Connection con) throws Exception { - Session s = con.createSession(false, Session.AUTO_ACKNOWLEDGE); - return s.createDurableSubscriber((Topic) destination, "TestFred"); - } - - protected void spawnConsumer() { - Thread thread = new Thread(new Runnable() { - @Override - public void run() { - try { - Connection consumerConnection = createConsumerConnection(); - MessageConsumer consumer = createConsumer(consumerConnection); - // consume some messages - - for (int i = 0; i < firstBatch; i++) { - Message msg = consumer.receive(RECEIVE_TIMEOUT); - if (msg != null) { - // log.info("GOT: " + msg); - messagesReceived.incrementAndGet(); - } - } - synchronized (closeBroker) { - closeBroker.set(true); - closeBroker.notify(); - } - Thread.sleep(2000); - for (int i = firstBatch; i < MESSAGE_COUNT; i++) { - Message msg = consumer.receive(RECEIVE_TIMEOUT); - // log.info("GOT: " + msg); - if (msg != null) { - messagesReceived.incrementAndGet(); - } - } - consumerConnection.close(); - synchronized (messagesReceived) { - messagesReceived.notify(); - } - } catch (Throwable e) { - e.printStackTrace(); - } - } - }); - thread.start(); - } - - public void testReconnect() throws Exception { - startBroker(true); - // register an interest as a durable subscriber - Connection consumerConnection = createConsumerConnection(); - createConsumer(consumerConnection); - consumerConnection.close(); - // send some messages ... - Connection connection = createConnection(); - connection.setClientID(idGen.generateId()); - connection.start(); - Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = producerSession.createProducer(destination); - TextMessage msg = producerSession.createTextMessage(); - for (int i = 0; i < MESSAGE_COUNT; i++) { - msg.setText("msg: " + i); - producer.send(msg); - } - connection.close(); - spawnConsumer(); - synchronized (closeBroker) { - while (!closeBroker.get()) { - closeBroker.wait(); - } - } - // System.err.println("Stopping broker"); - broker.stop(); - startBroker(false); - // System.err.println("Started Broker again"); - synchronized (messagesReceived) { - while (messagesReceived.get() < MESSAGE_COUNT) { - messagesReceived.wait(60000); - } - } - // assertTrue(messagesReceived.get() == MESSAGE_COUNT); - int count = messagesReceived.get(); - assertTrue("Not enough messages received: " + count, count > firstBatch); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyNoAdvisoryNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyNoAdvisoryNetworkTest.java deleted file mode 100644 index 32b5037bd5..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyNoAdvisoryNetworkTest.java +++ /dev/null @@ -1,278 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLStreamHandler; -import java.net.URLStreamHandlerFactory; -import java.nio.charset.StandardCharsets; -import java.util.Map; -import java.util.Vector; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ActiveMQSession; -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.broker.region.RegionBroker; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTempQueue; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.util.Wait; -import org.apache.activemq.xbean.XBeanBrokerFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class RequestReplyNoAdvisoryNetworkTest extends JmsMultipleBrokersTestSupport { - - private static final transient Logger LOG = LoggerFactory.getLogger(RequestReplyNoAdvisoryNetworkTest.class); - - Vector brokers = new Vector<>(); - BrokerService a, b; - ActiveMQQueue sendQ = new ActiveMQQueue("sendQ"); - static final String connectionIdMarker = "ID:marker."; - ActiveMQTempQueue replyQWildcard = new ActiveMQTempQueue(connectionIdMarker + ">"); - private final long receiveTimeout = 30000; - - public void testNonAdvisoryNetworkRequestReplyXmlConfig() throws Exception { - final String xmlConfigString = new String("" + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - ""); - final String localProtocolScheme = "inline"; - URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() { - @Override - public URLStreamHandler createURLStreamHandler(String protocol) { - if (localProtocolScheme.equalsIgnoreCase(protocol)) { - return new URLStreamHandler() { - @Override - protected URLConnection openConnection(URL u) throws IOException { - return new URLConnection(u) { - @Override - public void connect() throws IOException { - } - - @Override - public InputStream getInputStream() throws IOException { - return new ByteArrayInputStream(xmlConfigString.replace("%HOST%", url.getFile()).getBytes(StandardCharsets.UTF_8)); - } - }; - } - }; - } - return null; - } - }); - a = new XBeanBrokerFactory().createBroker(new URI("xbean:" + localProtocolScheme + ":A")); - b = new XBeanBrokerFactory().createBroker(new URI("xbean:" + localProtocolScheme + ":B")); - brokers.add(a); - brokers.add(b); - - doTestNonAdvisoryNetworkRequestReply(); - } - - public void testNonAdvisoryNetworkRequestReply() throws Exception { - createBridgeAndStartBrokers(); - doTestNonAdvisoryNetworkRequestReply(); - } - - public void testNonAdvisoryNetworkRequestReplyWithPIM() throws Exception { - a = configureBroker("A"); - b = configureBroker("B"); - BrokerService hub = configureBroker("M"); - hub.setAllowTempAutoCreationOnSend(true); - configureForPiggyInTheMiddle(bridge(a, hub)); - configureForPiggyInTheMiddle(bridge(b, hub)); - - startBrokers(); - - waitForBridgeFormation(hub, 2, 0); - doTestNonAdvisoryNetworkRequestReply(); - } - - private void configureForPiggyInTheMiddle(NetworkConnector bridge) { - bridge.setDuplex(true); - bridge.setNetworkTTL(2); - } - - public void doTestNonAdvisoryNetworkRequestReply() throws Exception { - - waitForBridgeFormation(a, 1, 0); - waitForBridgeFormation(b, 1, 0); - - ActiveMQConnectionFactory sendFactory = createConnectionFactory(a); - ActiveMQConnection sendConnection = createConnection(sendFactory); - - ActiveMQSession sendSession = (ActiveMQSession) sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = sendSession.createProducer(sendQ); - ActiveMQTempQueue realReplyQ = (ActiveMQTempQueue) sendSession.createTemporaryQueue(); - TextMessage message = sendSession.createTextMessage("1"); - message.setJMSReplyTo(realReplyQ); - producer.send(message); - LOG.info("request sent"); - - // responder - ActiveMQConnectionFactory consumerFactory = createConnectionFactory(b); - ActiveMQConnection consumerConnection = createConnection(consumerFactory); - - ActiveMQSession consumerSession = (ActiveMQSession) consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = consumerSession.createConsumer(sendQ); - TextMessage received = (TextMessage) consumer.receive(receiveTimeout); - assertNotNull("got request from sender ok", received); - - LOG.info("got request, sending reply"); - - MessageProducer consumerProducer = consumerSession.createProducer(received.getJMSReplyTo()); - consumerProducer.send(consumerSession.createTextMessage("got " + received.getText())); - // temp dest on reply broker tied to this connection, setOptimizedDispatch=true ensures - // message gets delivered before destination is removed - consumerConnection.close(); - - // reply consumer - MessageConsumer replyConsumer = sendSession.createConsumer(realReplyQ); - TextMessage reply = (TextMessage) replyConsumer.receive(receiveTimeout); - assertNotNull("expected reply message", reply); - assertEquals("text is as expected", "got 1", reply.getText()); - sendConnection.close(); - - LOG.info("checking for dangling temp destinations"); - // ensure all temp dests get cleaned up on all brokers - for (BrokerService brokerService : brokers) { - final RegionBroker regionBroker = (RegionBroker) brokerService.getRegionBroker(); - assertTrue("all temps are gone on " + regionBroker.getBrokerName(), Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - Map tempTopics = regionBroker.getTempTopicRegion().getDestinationMap(); - LOG.info("temp topics on " + regionBroker.getBrokerName() + ", " + tempTopics); - Map tempQ = regionBroker.getTempQueueRegion().getDestinationMap(); - LOG.info("temp queues on " + regionBroker.getBrokerName() + ", " + tempQ); - return tempQ.isEmpty() && tempTopics.isEmpty(); - } - })); - } - } - - private ActiveMQConnection createConnection(ActiveMQConnectionFactory factory) throws Exception { - ActiveMQConnection c = (ActiveMQConnection) factory.createConnection(); - c.start(); - return c; - } - - private ActiveMQConnectionFactory createConnectionFactory(BrokerService brokerService) throws Exception { - String target = brokerService.getTransportConnectors().get(0).getPublishableConnectString(); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(target); - factory.setWatchTopicAdvisories(false); - factory.setConnectionIDPrefix(connectionIdMarker + brokerService.getBrokerName()); - return factory; - } - - public void createBridgeAndStartBrokers() throws Exception { - a = configureBroker("A"); - b = configureBroker("B"); - bridge(a, b); - bridge(b, a); - startBrokers(); - } - - private void startBrokers() throws Exception { - for (BrokerService broker : brokers) { - broker.start(); - } - } - - @Override - public void tearDown() throws Exception { - for (BrokerService broker : brokers) { - broker.stop(); - } - brokers.clear(); - } - - private NetworkConnector bridge(BrokerService from, BrokerService to) throws Exception { - TransportConnector toConnector = to.getTransportConnectors().get(0); - NetworkConnector bridge = from.addNetworkConnector("static://" + toConnector.getPublishableConnectString()); - bridge.addStaticallyIncludedDestination(sendQ); - bridge.addStaticallyIncludedDestination(replyQWildcard); - return bridge; - } - - private BrokerService configureBroker(String brokerName) throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName(brokerName); - broker.setAdvisorySupport(false); - broker.setPersistent(false); - broker.setUseJmx(false); - broker.setSchedulePeriodForDestinationPurge(1000); - broker.setAllowTempAutoCreationOnSend(true); - - PolicyMap map = new PolicyMap(); - PolicyEntry tempReplyQPolicy = new PolicyEntry(); - tempReplyQPolicy.setOptimizedDispatch(true); - tempReplyQPolicy.setGcInactiveDestinations(true); - tempReplyQPolicy.setGcWithNetworkConsumers(true); - tempReplyQPolicy.setInactiveTimeoutBeforeGC(1000); - map.put(replyQWildcard, tempReplyQPolicy); - broker.setDestinationPolicy(map); - - broker.addConnector("tcp://localhost:0"); - brokers.add(broker); - return broker; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyTempDestRemovalAdvisoryRaceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyTempDestRemovalAdvisoryRaceTest.java deleted file mode 100644 index cb3203a882..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyTempDestRemovalAdvisoryRaceTest.java +++ /dev/null @@ -1,474 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.net.URI; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Random; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; - -import junit.framework.Test; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.advisory.AdvisorySupport; -import org.apache.activemq.broker.region.policy.DeadLetterStrategy; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.broker.region.policy.PriorityDispatchPolicy; -import org.apache.activemq.broker.region.policy.SharedDeadLetterStrategy; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTempTopic; -import org.apache.activemq.command.ActiveMQTextMessage; -import org.apache.activemq.network.DemandForwardingBridgeSupport; -import org.apache.activemq.network.NetworkBridge; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.util.DefaultTestAppender; -import org.apache.log4j.Appender; -import org.apache.log4j.Level; -import org.apache.log4j.spi.LoggingEvent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Christian Posta - */ -public class RequestReplyTempDestRemovalAdvisoryRaceTest extends JmsMultipleBrokersTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(RequestReplyTempDestRemovalAdvisoryRaceTest.class); - - private static final String BROKER_A = "BrokerA"; - private static final String BROKER_B = "BrokerB"; - private static final String BROKER_C = "BrokerC"; - - private static final int NUM_RESPONDENTS = 1; - private static final int NUM_SENDS = 1; - private static final int RANDOM_SLEEP_FOR_RESPONDENT_MS = 0; - private static final int RANDOM_SLEEP_FOR_SENDER_MS = 1; - private static final String QUEUE_NAME = "foo.queue"; - private static String[] TEST_ITERATIONS = new String[]{QUEUE_NAME + "0", QUEUE_NAME + "1", QUEUE_NAME + "2", QUEUE_NAME + "3"}; - - final AtomicLong messageCount = new AtomicLong(0); - final AtomicLong respondentSendError = new AtomicLong(0); - final AtomicLong responseReceived = new AtomicLong(0); - final AtomicLong sendsWithNoConsumers = new AtomicLong(0); - final AtomicLong forwardFailures = new AtomicLong(0); - - protected final AtomicBoolean shutdown = new AtomicBoolean(false); - HashSet networkConnectors = new HashSet<>(); - HashSet advisoryConsumerConnections = new HashSet<>(); - Appender slowDownAppender; - - CountDownLatch consumerDemandExists; - - protected boolean useDuplex = false; - - public static Test suite() { - return suite(RequestReplyTempDestRemovalAdvisoryRaceTest.class); - } - - /** - * Notes: to reliably reproduce use debugger... set a "thread" breakpoint at line 679 in DemandForwardingBridgeSupport, - * and only break on the "2nd" pass (broker C's bridge). Allow debugging to continue shortly after hitting - * the breakpoint, for this test we use a logging appender to implement the pause, - * it fails most of the time, hence the combos - */ - public void initCombos() { - addCombinationValues("QUEUE_NAME", TEST_ITERATIONS); - } - - public void testTempDestRaceDuplex() throws Exception { - // duplex - useDuplex = true; - bridgeBrokers(BROKER_A, BROKER_B, false, 3); - bridgeBrokers(BROKER_B, BROKER_C, false, 3); - - startAllBrokers(); - - waitForBridgeFormation(1); - - HashSet bridgesStart = new HashSet<>(); - for (NetworkConnector networkConnector : networkConnectors) { - bridgesStart.addAll(networkConnector.activeBridges()); - } - LOG.info("Bridges start:" + bridgesStart); - - slowDownAdvisoryDispatch(); - noConsumerAdvisory(); - forwardFailureAdvisory(); - - // set up respondents - ExecutorService respondentThreadPool = Executors.newFixedThreadPool(50); - BrokerItem brokerA = brokers.get(BROKER_A); - ActiveMQConnectionFactory brokerAFactory = new ActiveMQConnectionFactory(brokerA.broker.getTransportConnectorByScheme("tcp").getName() + "?jms.watchTopicAdvisories=false"); - brokerAFactory.setAlwaysSyncSend(true); - for (int i = 0; i < NUM_RESPONDENTS; i++) { - respondentThreadPool.execute(new EchoRespondent(brokerAFactory)); - } - - // fire off sends - ExecutorService senderThreadPool = Executors.newCachedThreadPool(); - BrokerItem brokerC = brokers.get(BROKER_C); - ActiveMQConnectionFactory brokerCFactory = new ActiveMQConnectionFactory(brokerC.broker.getTransportConnectorByScheme("tcp").getName() + "?jms.watchTopicAdvisories=false"); - for (int i = 0; i < NUM_SENDS; i++) { - senderThreadPool.execute(new MessageSender(brokerCFactory)); - } - - senderThreadPool.shutdown(); - senderThreadPool.awaitTermination(30, TimeUnit.SECONDS); - TimeUnit.SECONDS.sleep(15); - LOG.info("shutting down"); - shutdown.compareAndSet(false, true); - - HashSet bridgesEnd = new HashSet<>(); - for (NetworkConnector networkConnector : networkConnectors) { - bridgesEnd.addAll(networkConnector.activeBridges()); - } - LOG.info("Bridges end:" + bridgesEnd); - - assertEquals("no new bridges created", bridgesStart, bridgesEnd); - - // validate success or error of dlq - LOG.info("received: " + responseReceived.get() + ", respondent error: " + respondentSendError.get() + ", noConsumerCount: " + sendsWithNoConsumers.get() + ", forwardFailures: " + forwardFailures.get()); - assertEquals("success or error", NUM_SENDS, respondentSendError.get() + forwardFailures.get() + responseReceived.get() + sendsWithNoConsumers.get()); - - } - - private void forwardFailureAdvisory() throws JMSException { - for (BrokerItem item : brokers.values()) { - ActiveMQConnectionFactory brokerAFactory = new ActiveMQConnectionFactory(item.broker.getTransportConnectorByScheme("tcp").getName() + "?jms.watchTopicAdvisories=false"); - Connection connection = brokerAFactory.createConnection(); - connection.start(); - connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createConsumer(AdvisorySupport.getNetworkBridgeForwardFailureAdvisoryTopic()).setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - forwardFailures.incrementAndGet(); - } - }); - } - } - - private void noConsumerAdvisory() throws JMSException { - for (BrokerItem item : brokers.values()) { - ActiveMQConnectionFactory brokerAFactory = new ActiveMQConnectionFactory(item.broker.getTransportConnectorByScheme("tcp").getName() + "?jms.watchTopicAdvisories=false"); - Connection connection = brokerAFactory.createConnection(); - connection.start(); - connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createConsumer(AdvisorySupport.getNoTopicConsumersAdvisoryTopic(new ActiveMQTempTopic(">"))).setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - sendsWithNoConsumers.incrementAndGet(); - } - }); - } - } - - public void testTempDestRace() throws Exception { - // non duplex - bridgeBrokers(BROKER_A, BROKER_B, false, 3); - bridgeBrokers(BROKER_B, BROKER_A, false, 3); - bridgeBrokers(BROKER_B, BROKER_C, false, 3); - bridgeBrokers(BROKER_C, BROKER_B, false, 3); - - startAllBrokers(); - - waitForBridgeFormation(1); - - HashSet bridgesStart = new HashSet<>(); - for (NetworkConnector networkConnector : networkConnectors) { - bridgesStart.addAll(networkConnector.activeBridges()); - } - - slowDownAdvisoryDispatch(); - noConsumerAdvisory(); - forwardFailureAdvisory(); - - // set up respondents - ExecutorService respondentThreadPool = Executors.newFixedThreadPool(50); - BrokerItem brokerA = brokers.get(BROKER_A); - ActiveMQConnectionFactory brokerAFactory = new ActiveMQConnectionFactory(brokerA.broker.getTransportConnectorByScheme("tcp").getName() + "?jms.watchTopicAdvisories=false"); - brokerAFactory.setAlwaysSyncSend(true); - for (int i = 0; i < NUM_RESPONDENTS; i++) { - respondentThreadPool.execute(new EchoRespondent(brokerAFactory)); - } - - // fire off sends - ExecutorService senderThreadPool = Executors.newCachedThreadPool(); - BrokerItem brokerC = brokers.get(BROKER_C); - ActiveMQConnectionFactory brokerCFactory = new ActiveMQConnectionFactory(brokerC.broker.getTransportConnectorByScheme("tcp").getName() + "?jms.watchTopicAdvisories=false"); - for (int i = 0; i < NUM_SENDS; i++) { - senderThreadPool.execute(new MessageSender(brokerCFactory)); - } - - senderThreadPool.shutdown(); - senderThreadPool.awaitTermination(30, TimeUnit.SECONDS); - TimeUnit.SECONDS.sleep(10); - LOG.info("shutting down"); - shutdown.compareAndSet(false, true); - - HashSet bridgesEnd = new HashSet<>(); - for (NetworkConnector networkConnector : networkConnectors) { - bridgesEnd.addAll(networkConnector.activeBridges()); - } - assertEquals("no new bridges created", bridgesStart, bridgesEnd); - - // validate success or error or dlq - LOG.info("received: " + responseReceived.get() + ", respondent error: " + respondentSendError.get() + ", noConsumerCount: " + sendsWithNoConsumers.get() + ", forwardFailures: " + forwardFailures.get()); - assertEquals("success or error", NUM_SENDS, respondentSendError.get() + forwardFailures.get() + responseReceived.get() + sendsWithNoConsumers.get()); - - } - - private void slowDownAdvisoryDispatch() throws Exception { - - org.apache.log4j.Logger.getLogger(DemandForwardingBridgeSupport.class).setLevel(Level.DEBUG); - - // instrument a logger to block the processing of a remove sub advisory - // simulate a slow thread - slowDownAppender = new DefaultTestAppender() { - @Override - public void doAppend(LoggingEvent loggingEvent) { - if (Level.DEBUG.equals(loggingEvent.getLevel())) { - String message = loggingEvent.getMessage().toString(); - if (message.startsWith("BrokerB") && message.contains("remove local subscription")) { - // sleep for a bit - try { - consumerDemandExists.countDown(); - System.err.println("Sleeping on receipt of remove info debug message: " + message); - TimeUnit.SECONDS.sleep(2); - } catch (Exception ignored) { - } - } - - } - } - }; - - org.apache.log4j.Logger.getRootLogger().addAppender(slowDownAppender); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - responseReceived.set(0); - respondentSendError.set(0); - forwardFailures.set(0); - sendsWithNoConsumers.set(0); - networkConnectors.clear(); - advisoryConsumerConnections.clear(); - consumerDemandExists = new CountDownLatch(1); - createBroker(new URI("broker:(tcp://localhost:0)/" + BROKER_A + "?persistent=false&useJmx=false")).setDedicatedTaskRunner(false); - createBroker(new URI("broker:(tcp://localhost:0)/" + BROKER_B + "?persistent=false&useJmx=false")).setDedicatedTaskRunner(false); - createBroker(new URI("broker:(tcp://localhost:0)/" + BROKER_C + "?persistent=false&useJmx=false")).setDedicatedTaskRunner(false); - - PolicyMap map = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setSendAdvisoryIfNoConsumers(true); - DeadLetterStrategy deadletterStrategy = new SharedDeadLetterStrategy(); - deadletterStrategy.setProcessNonPersistent(true); - defaultEntry.setDeadLetterStrategy(deadletterStrategy); - defaultEntry.setDispatchPolicy(new PriorityDispatchPolicy()); - map.put(new ActiveMQTempTopic(">"), defaultEntry); - - for (BrokerItem item : brokers.values()) { - item.broker.setDestinationPolicy(map); - } - } - - @Override - protected void tearDown() throws Exception { - if (slowDownAppender != null) { - org.apache.log4j.Logger.getRootLogger().removeAppender(slowDownAppender); - } - for (Connection connection : advisoryConsumerConnections) { - connection.close(); - } - super.tearDown(); - } - - protected NetworkConnector bridgeBrokers(String localBrokerName, - String remoteBrokerName, - boolean dynamicOnly, - int networkTTL) throws Exception { - NetworkConnector connector = super.bridgeBrokers(localBrokerName, remoteBrokerName, dynamicOnly, networkTTL, true); - connector.setBridgeTempDestinations(true); - connector.setAdvisoryForFailedForward(true); - connector.setDuplex(useDuplex); - connector.setAlwaysSyncSend(true); - networkConnectors.add(connector); - return connector; - } - - abstract class MessageClient { - - protected Connection connection; - protected Session session; - protected MessageConsumer consumer; - protected MessageProducer producer; - protected Random random; - protected int timeToSleep; - - // set up the connection and session - public MessageClient(ActiveMQConnectionFactory factory, int timeToSleep) throws Exception { - this.connection = factory.createConnection(); - this.session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - this.timeToSleep = timeToSleep; - this.random = new Random(System.currentTimeMillis()); - preInit(); - initProducer(); - initConsumer(); - this.connection.start(); - } - - protected void preInit() throws JMSException { - - } - - abstract protected void initProducer() throws JMSException; - - abstract protected void initConsumer() throws JMSException; - } - - class MessageSender extends MessageClient implements Runnable { - - protected Destination tempDest; - - public MessageSender(ActiveMQConnectionFactory factory) throws Exception { - super(factory, RANDOM_SLEEP_FOR_SENDER_MS); - } - - @Override - public void run() { - // create a message - try { - TextMessage message = session.createTextMessage("request: message #" + messageCount.getAndIncrement()); - message.setJMSReplyTo(tempDest); - producer.send(message); - LOG.info("SENDER: Message [" + message.getText() + "] has been sent."); - - Message incomingMessage = consumer.receive(timeToSleep); - if (incomingMessage instanceof TextMessage) { - try { - LOG.info("SENDER: Got a response from echo service!" + ((TextMessage) incomingMessage).getText()); - responseReceived.incrementAndGet(); - } catch (JMSException e) { - LOG.error("SENDER: might want to see why i'm getting non-text messages..." + incomingMessage, e); - } - } else { - LOG.info("SENDER: Did not get a response this time"); - } - - } catch (JMSException e) { - LOG.error("SENDER: Could not complete message sending properly: " + e.getMessage()); - } finally { - try { - producer.close(); - consumer.close(); - session.close(); - connection.close(); - } catch (JMSException e) { - e.printStackTrace(); - } - } - } - - @Override - protected void preInit() throws JMSException { - this.tempDest = session.createTemporaryTopic(); - - } - - @Override - protected void initProducer() throws JMSException { - this.producer = session.createProducer(new ActiveMQQueue(QUEUE_NAME)); - } - - @Override - protected void initConsumer() throws JMSException { - this.consumer = session.createConsumer(tempDest); - LOG.info("consumer for: " + tempDest + ", " + consumer); - - } - - } - - class EchoRespondent extends MessageClient implements Runnable { - - public EchoRespondent(ActiveMQConnectionFactory factory) throws Exception { - super(factory, RANDOM_SLEEP_FOR_RESPONDENT_MS); - } - - @Override - public void run() { - try { - LOG.info("RESPONDENT LISTENING"); - while (!shutdown.get()) { - Message incomingMessage = consumer.receive(1000); - if (incomingMessage instanceof TextMessage) { - ActiveMQTextMessage textMessage = (ActiveMQTextMessage) incomingMessage; - try { - LOG.info("RESPONDENT: Received a message: [" + textMessage.getText() + "]" + Arrays.asList(textMessage.getBrokerPath())); - Message message = session.createTextMessage("reply: " + textMessage.getText()); - Destination replyTo = incomingMessage.getJMSReplyTo(); - TimeUnit.MILLISECONDS.sleep(timeToSleep); - consumerDemandExists.await(5, TimeUnit.SECONDS); - try { - producer.send(replyTo, message); - LOG.info("RESPONDENT: sent reply:" + message.getJMSMessageID() + " back to: " + replyTo); - } catch (JMSException e) { - LOG.error("RESPONDENT: could not send reply message: " + e.getLocalizedMessage(), e); - respondentSendError.incrementAndGet(); - } - } catch (JMSException e) { - LOG.error("RESPONDENT: could not create the reply message: " + e.getLocalizedMessage(), e); - } catch (InterruptedException e) { - LOG.info("RESPONDENT could not generate a random number"); - } - } - } - } catch (JMSException e) { - LOG.info("RESPONDENT: Could not set the message listener on the respondent"); - } - } - - @Override - protected void initProducer() throws JMSException { - this.producer = session.createProducer(null); - // so that we can get an advisory on sending with no consumers - this.producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - } - - @Override - protected void initConsumer() throws JMSException { - this.consumer = session.createConsumer(new ActiveMQQueue(QUEUE_NAME)); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyToTopicViaThreeNetworkHopsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyToTopicViaThreeNetworkHopsTest.java deleted file mode 100644 index 8bd080159a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/RequestReplyToTopicViaThreeNetworkHopsTest.java +++ /dev/null @@ -1,983 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQSession; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.network.DiscoveryNetworkConnector; -import org.apache.activemq.network.NetworkConnector; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Test; - -import static org.junit.Assert.assertTrue; - -public class RequestReplyToTopicViaThreeNetworkHopsTest { - - protected static final int CONCURRENT_CLIENT_COUNT = 5; - protected static final int CONCURRENT_SERVER_COUNT = 5; - protected static final int TOTAL_CLIENT_ITER = 10; - - protected static int Next_broker_num = 0; - protected EmbeddedTcpBroker edge1; - protected EmbeddedTcpBroker edge2; - protected EmbeddedTcpBroker core1; - protected EmbeddedTcpBroker core2; - - protected boolean testError = false; - protected boolean fatalTestError = false; - - protected int echoResponseFill = 0; // Number of "filler" response messages per request - - protected static Log LOG; - public boolean duplex = true; - - static { - LOG = LogFactory.getLog(RequestReplyToTopicViaThreeNetworkHopsTest.class); - } - - public RequestReplyToTopicViaThreeNetworkHopsTest() throws Exception { - edge1 = new EmbeddedTcpBroker("edge", 1); - edge2 = new EmbeddedTcpBroker("edge", 2); - core1 = new EmbeddedTcpBroker("core", 1); - core2 = new EmbeddedTcpBroker("core", 2); - - // duplex is necessary to serialise sends with consumer/destination creation - edge1.coreConnectTo(core1, duplex); - edge2.coreConnectTo(core2, duplex); - core1.coreConnectTo(core2, duplex); - } - - public void logMessage(String msg) { - System.out.println(msg); - System.out.flush(); - } - - public void testMessages(Session sess, - MessageProducer req_prod, - Destination resp_dest, - int num_msg) throws Exception { - MessageConsumer resp_cons; - TextMessage msg; - MessageClient cons_client; - int cur; - int tot_expected; - - resp_cons = sess.createConsumer(resp_dest); - - cons_client = new MessageClient(resp_cons, num_msg); - cons_client.start(); - - cur = 0; - while ((cur < num_msg) && (!fatalTestError)) { - msg = sess.createTextMessage("MSG AAAA " + cur); - msg.setIntProperty("SEQ", 100 + cur); - msg.setStringProperty("TEST", "TOPO"); - msg.setJMSReplyTo(resp_dest); - - if (cur == (num_msg - 1)) - msg.setBooleanProperty("end-of-response", true); - - sendWithRetryOnDeletedDest(req_prod, msg); - LOG.debug("Sent:" + msg); - - cur++; - } - - // - // Give the consumer some time to receive the response. - // - cons_client.waitShutdown(5000); - - // - // Now shutdown the consumer if it's still running. - // - if (cons_client.shutdown()) - LOG.debug("Consumer client shutdown complete"); - else - LOG.debug("Consumer client shutdown incomplete!!!"); - - // - // Check that the correct number of messages was received. - // - tot_expected = num_msg * (echoResponseFill + 1); - - if (cons_client.getNumMsgReceived() == tot_expected) { - LOG.debug("Have " + tot_expected + " messages, as-expected"); - } else { - testError = true; - - if (cons_client.getNumMsgReceived() == 0) - fatalTestError = true; - - LOG.error("Have " + cons_client.getNumMsgReceived() + " messages; expected " + tot_expected + " on destination " + resp_dest); - } - - resp_cons.close(); - } - - protected void sendWithRetryOnDeletedDest(MessageProducer prod, Message msg) throws JMSException { - try { - if (LOG.isDebugEnabled()) - LOG.debug("SENDING REQUEST message " + msg); - - prod.send(msg); - } catch (JMSException jms_exc) { - System.out.println("AAA: " + jms_exc.getMessage()); - throw jms_exc; - } - } - - /** - * Test one destination between the given "producer broker" and "consumer broker" specified. - */ - public void testOneDest(Connection conn, Session sess, Destination cons_dest, int num_msg) throws Exception { - Destination prod_dest; - MessageProducer msg_prod; - - // - // Create the Producer to the echo request Queue - // - LOG.trace("Creating echo queue and producer"); - prod_dest = sess.createQueue("echo"); - msg_prod = sess.createProducer(prod_dest); - - // - // Pass messages around. - // - testMessages(sess, msg_prod, cons_dest, num_msg); - - msg_prod.close(); - } - - /** - * TEST TEMPORARY TOPICS - */ - public void testTempTopic(String prod_broker_url, String cons_broker_url) throws Exception { - Connection conn; - Session sess; - Destination cons_dest; - int num_msg; - - num_msg = 5; - - LOG.debug("TESTING TEMP TOPICS " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)"); - - // - // Connect to the bus. - // - conn = createConnection(cons_broker_url); - conn.start(); - sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // - // Create the destination on which messages are being tested. - // - LOG.trace("Creating destination"); - cons_dest = sess.createTemporaryTopic(); - - testOneDest(conn, sess, cons_dest, num_msg); - - // - // Cleanup - // - sess.close(); - conn.close(); - } - - /** - * TEST TOPICS - */ - public void testTopic(String prod_broker_url, String cons_broker_url) throws Exception { - int num_msg; - - Connection conn; - Session sess; - String topic_name; - - Destination cons_dest; - - num_msg = 5; - - LOG.info("TESTING TOPICS " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)"); - - conn = createConnection(cons_broker_url); - conn.start(); - sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // - // Create the destination on which messages are being tested. - // - topic_name = "topotest2.perm.topic"; - LOG.trace("Removing existing Topic"); - removeTopic(conn, topic_name); - LOG.trace("Creating Topic, " + topic_name); - cons_dest = sess.createTopic(topic_name); - - testOneDest(conn, sess, cons_dest, num_msg); - - // - // Cleanup - // - removeTopic(conn, topic_name); - sess.close(); - conn.close(); - } - - /** - * TEST TEMPORARY QUEUES - */ - public void testTempQueue(String prod_broker_url, String cons_broker_url) throws Exception { - int num_msg; - - Connection conn; - Session sess; - - Destination cons_dest; - - num_msg = 5; - - LOG.info("TESTING TEMP QUEUES " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)"); - - // - // Connect to the bus. - // - conn = createConnection(cons_broker_url); - conn.start(); - sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // - // Create the destination on which messages are being tested. - // - LOG.trace("Creating destination"); - cons_dest = sess.createTemporaryQueue(); - - testOneDest(conn, sess, cons_dest, num_msg); - - // - // Cleanup - // - sess.close(); - conn.close(); - } - - /** - * TEST QUEUES - */ - public void testQueue(String prod_broker_url, String cons_broker_url) throws Exception { - int num_msg; - - Connection conn; - Session sess; - String queue_name; - - Destination cons_dest; - - num_msg = 5; - - LOG.info("TESTING QUEUES " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg + " messages)"); - - conn = createConnection(cons_broker_url); - conn.start(); - sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // - // Create the destination on which messages are being tested. - // - queue_name = "topotest2.perm.queue"; - LOG.trace("Removing existing Queue"); - removeQueue(conn, queue_name); - LOG.trace("Creating Queue, " + queue_name); - cons_dest = sess.createQueue(queue_name); - - testOneDest(conn, sess, cons_dest, num_msg); - - removeQueue(conn, queue_name); - sess.close(); - conn.close(); - } - - @Test - public void runWithTempTopicReplyTo() throws Exception { - EchoService echo_svc; - TopicTrafficGenerator traffic_gen; - Thread start1; - Thread start2; - Thread start3; - Thread start4; - ThreadPoolExecutor clientExecPool; - final CountDownLatch clientCompletionLatch; - int iter; - - fatalTestError = false; - testError = false; - - // - // Execute up to 20 clients at a time to simulate that load. - // - - clientExecPool = new ThreadPoolExecutor(CONCURRENT_CLIENT_COUNT, CONCURRENT_CLIENT_COUNT, 0, TimeUnit.SECONDS, new ArrayBlockingQueue(10000)); - clientCompletionLatch = new CountDownLatch(TOTAL_CLIENT_ITER); - - // Use threads to avoid startup deadlock since the first broker started waits until - // it knows the name of the remote broker before finishing its startup, which means - // the remote must already be running. - - start1 = new Thread() { - @Override - public void run() { - try { - edge1.start(); - } catch (Exception ex) { - LOG.error(null, ex); - } - } - }; - - start2 = new Thread() { - @Override - public void run() { - try { - edge2.start(); - } catch (Exception ex) { - LOG.error(null, ex); - } - } - }; - - start3 = new Thread() { - @Override - public void run() { - try { - core1.start(); - } catch (Exception ex) { - LOG.error(null, ex); - } - } - }; - - start4 = new Thread() { - @Override - public void run() { - try { - core2.start(); - } catch (Exception ex) { - LOG.error(null, ex); - } - } - }; - - start1.start(); - start2.start(); - start3.start(); - start4.start(); - - start1.join(); - start2.join(); - start3.join(); - start4.join(); - - traffic_gen = new TopicTrafficGenerator(edge1.getConnectionUrl(), edge2.getConnectionUrl()); - traffic_gen.start(); - - // - // Now start the echo service with that queue. - // - echo_svc = new EchoService("echo", edge1.getConnectionUrl()); - echo_svc.start(); - - // - // Run the tests on Temp Topics. - // - - LOG.info("** STARTING TEMP TOPIC TESTS"); - iter = 0; - while ((iter < TOTAL_CLIENT_ITER) && (!fatalTestError)) { - clientExecPool.execute(new Runnable() { - @Override - public void run() { - try { - RequestReplyToTopicViaThreeNetworkHopsTest.this.testTempTopic(edge1.getConnectionUrl(), edge2.getConnectionUrl()); - } catch (Exception exc) { - LOG.error("test exception", exc); - fatalTestError = true; - testError = true; - } - - clientCompletionLatch.countDown(); - } - }); - - iter++; - } - - boolean allDoneOnTime = clientCompletionLatch.await(20, TimeUnit.MINUTES); - - LOG.info("** FINISHED TEMP TOPIC TESTS AFTER " + iter + " ITERATIONS, testError:" + testError + ", fatal: " + fatalTestError + ", onTime:" + allDoneOnTime); - - Thread.sleep(100); - - echo_svc.shutdown(); - traffic_gen.shutdown(); - - shutdown(); - - assertTrue("test completed in time", allDoneOnTime); - assertTrue("no errors", !testError); - } - - public void shutdown() throws Exception { - edge1.stop(); - edge2.stop(); - core1.stop(); - core2.stop(); - } - - protected Connection createConnection(String url) throws Exception { - return org.apache.activemq.ActiveMQConnection.makeConnection(url); - } - - protected static void removeQueue(Connection conn, String dest_name) throws java.lang.Exception { - org.apache.activemq.command.ActiveMQDestination dest; - - if (conn instanceof org.apache.activemq.ActiveMQConnection) { - dest = org.apache.activemq.command.ActiveMQDestination.createDestination(dest_name, org.apache.activemq.command.ActiveMQDestination.QUEUE_TYPE); - ((org.apache.activemq.ActiveMQConnection) conn).destroyDestination(dest); - } - } - - protected static void removeTopic(Connection conn, String dest_name) throws java.lang.Exception { - org.apache.activemq.command.ActiveMQDestination dest; - - if (conn instanceof org.apache.activemq.ActiveMQConnection) { - dest = org.apache.activemq.command.ActiveMQDestination.createDestination(dest_name, org.apache.activemq.command.ActiveMQDestination.TOPIC_TYPE); - ((org.apache.activemq.ActiveMQConnection) conn).destroyDestination(dest); - } - } - - public static String fmtMsgInfo(Message msg) throws Exception { - StringBuilder msg_desc; - String prop; - Enumeration prop_enum; - - msg_desc = new StringBuilder(); - msg_desc = new StringBuilder(); - - if (msg instanceof TextMessage) { - msg_desc.append(((TextMessage) msg).getText()); - } else { - msg_desc.append("["); - msg_desc.append(msg.getClass().getName()); - msg_desc.append("]"); - } - - prop_enum = msg.getPropertyNames(); - while (prop_enum.hasMoreElements()) { - prop = (String) prop_enum.nextElement(); - msg_desc.append("; "); - msg_desc.append(prop); - msg_desc.append("="); - msg_desc.append(msg.getStringProperty(prop)); - } - - return msg_desc.toString(); - } - - protected class EmbeddedTcpBroker { - - protected BrokerService brokerSvc; - protected int brokerNum; - protected String brokerName; - protected String brokerId; - protected int port; - protected String tcpUrl; - protected String fullUrl; - - public EmbeddedTcpBroker(String name, int number) throws Exception { - brokerSvc = new BrokerService(); - - synchronized (this.getClass()) { - brokerNum = Next_broker_num; - Next_broker_num++; - } - - brokerName = name + number; - brokerId = brokerName; - - brokerSvc.setBrokerName(brokerName); - brokerSvc.setBrokerId(brokerId); - - brokerSvc.setPersistent(false); - brokerSvc.setUseJmx(false); - - port = 60000 + (brokerNum * 10); - - tcpUrl = "tcp://127.0.0.1:" + Integer.toString(port); - fullUrl = tcpUrl + "?jms.watchTopicAdvisories=false"; - - brokerSvc.addConnector(tcpUrl); - } - - public Connection createConnection() throws URISyntaxException, JMSException { - Connection result; - - result = org.apache.activemq.ActiveMQConnection.makeConnection(this.fullUrl); - - return result; - } - - public String getConnectionUrl() { - return this.fullUrl; - } - - public void coreConnectTo(EmbeddedTcpBroker other, boolean duplex_f) throws Exception { - this.makeConnectionTo(other, duplex_f, true); - this.makeConnectionTo(other, duplex_f, false); - if (!duplex_f) { - other.makeConnectionTo(this, duplex_f, true); - other.makeConnectionTo(this, duplex_f, false); - } - } - - public void start() throws Exception { - brokerSvc.start(); - brokerSvc.waitUntilStarted(); - } - - public void stop() throws Exception { - brokerSvc.stop(); - } - - protected void makeConnectionTo(EmbeddedTcpBroker other, boolean duplex_f, boolean queue_f) throws Exception { - NetworkConnector nw_conn; - String prefix; - ActiveMQDestination excl_dest; - ArrayList excludes; - - nw_conn = new DiscoveryNetworkConnector(new URI("static:(" + other.tcpUrl + ")")); - nw_conn.setDuplex(duplex_f); - - if (queue_f) - nw_conn.setConduitSubscriptions(false); - else - nw_conn.setConduitSubscriptions(true); - - nw_conn.setNetworkTTL(3); - nw_conn.setSuppressDuplicateQueueSubscriptions(true); - nw_conn.setDecreaseNetworkConsumerPriority(true); - nw_conn.setBridgeTempDestinations(queue_f); - - if (queue_f) { - prefix = "queue"; - excl_dest = ActiveMQDestination.createDestination(">", ActiveMQDestination.TOPIC_TYPE); - } else { - prefix = "topic"; - excl_dest = ActiveMQDestination.createDestination(">", ActiveMQDestination.QUEUE_TYPE); - } - - excludes = new ArrayList<>(); - excludes.add(excl_dest); - nw_conn.setExcludedDestinations(excludes); - - if (duplex_f) - nw_conn.setName(this.brokerId + "<-" + prefix + "->" + other.brokerId); - else - nw_conn.setName(this.brokerId + "-" + prefix + "->" + other.brokerId); - - brokerSvc.addNetworkConnector(nw_conn); - } - } - - protected class MessageClient extends java.lang.Thread { - - protected MessageConsumer msgCons; - protected boolean shutdownInd; - protected int expectedCount; - protected int lastSeq = 0; - protected int msgCount = 0; - protected boolean haveFirstSeq; - protected CountDownLatch shutdownLatch; - - public MessageClient(MessageConsumer cons, int num_to_expect) { - msgCons = cons; - expectedCount = (num_to_expect * (echoResponseFill + 1)); - shutdownLatch = new CountDownLatch(1); - } - - @Override - public void run() { - CountDownLatch latch; - - try { - synchronized (this) { - latch = shutdownLatch; - } - - shutdownInd = false; - processMessages(); - - latch.countDown(); - } catch (Exception exc) { - LOG.error("message client error", exc); - } - } - - public void waitShutdown(long timeout) { - CountDownLatch latch; - - try { - synchronized (this) { - latch = shutdownLatch; - } - - if (latch != null) - latch.await(timeout, TimeUnit.MILLISECONDS); - else - LOG.info("echo client shutdown: client does not appear to be active"); - } catch (InterruptedException int_exc) { - LOG.warn("wait for message client shutdown interrupted", int_exc); - } - } - - public boolean shutdown() { - boolean down_ind; - - if (!shutdownInd) { - shutdownInd = true; - } - - waitShutdown(200); - - synchronized (this) { - if ((shutdownLatch == null) || (shutdownLatch.getCount() == 0)) - down_ind = true; - else - down_ind = false; - } - - return down_ind; - } - - public int getNumMsgReceived() { - return msgCount; - } - - protected void processMessages() throws Exception { - Message in_msg; - - haveFirstSeq = false; - - // - // Stop at shutdown time or after any test error is detected. - // - - while ((!shutdownInd) && (!fatalTestError)) { - in_msg = msgCons.receive(100); - - if (in_msg != null) { - msgCount++; - checkMessage(in_msg); - } - } - - msgCons.close(); - } - - protected void checkMessage(Message in_msg) throws Exception { - int seq; - - LOG.debug("received message " + fmtMsgInfo(in_msg) + " from " + in_msg.getJMSDestination()); - - // - // Only check messages with a sequence number. - // - - if (in_msg.propertyExists("SEQ")) { - seq = in_msg.getIntProperty("SEQ"); - - if ((haveFirstSeq) && (seq != (lastSeq + 1))) { - LOG.error("***ERROR*** incorrect sequence number; expected " + Integer.toString(lastSeq + 1) + " but have " + Integer.toString(seq)); - - testError = true; - } - - lastSeq = seq; - - if (msgCount > expectedCount) { - LOG.error("*** have more messages than expected; have " + msgCount + "; expect " + expectedCount); - - testError = true; - } - } - - if (in_msg.propertyExists("end-of-response")) { - LOG.trace("received end-of-response message"); - } - } - } - - /** - * - */ - protected class EchoService extends java.lang.Thread { - - protected String destName; - protected Connection jmsConn; - protected Session sess; - protected MessageConsumer msg_cons; - protected boolean Shutdown_ind; - - protected Destination req_dest; - - protected CountDownLatch waitShutdown; - - protected ThreadPoolExecutor processorPool; - - public EchoService(String dest, Connection broker_conn) throws Exception { - destName = dest; - jmsConn = broker_conn; - - Shutdown_ind = false; - - sess = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - req_dest = sess.createQueue(destName); - msg_cons = sess.createConsumer(req_dest); - - jmsConn.start(); - - waitShutdown = new CountDownLatch(1); - - processorPool = new ThreadPoolExecutor(CONCURRENT_SERVER_COUNT, CONCURRENT_SERVER_COUNT, 0, TimeUnit.SECONDS, new ArrayBlockingQueue(10000)); - } - - public EchoService(String dest, String broker_url) throws Exception { - this(dest, ActiveMQConnection.makeConnection(broker_url)); - } - - @Override - public void run() { - Message req; - - try { - LOG.info("STARTING ECHO SERVICE"); - - while (!Shutdown_ind) { - req = msg_cons.receive(100); - if (req != null) { - processorPool.execute(new EchoRequestProcessor(sess, req)); - } - } - } catch (Exception ex) { - LOG.error("error processing echo service requests", ex); - } finally { - LOG.info("shutting down test echo service"); - - try { - jmsConn.stop(); - } catch (javax.jms.JMSException jms_exc) { - LOG.warn("error on shutting down JMS connection", jms_exc); - } - - synchronized (this) { - waitShutdown.countDown(); - } - } - } - - /** - * Shut down the service, waiting up to 3 seconds for the service to terminate. - */ - public void shutdown() { - CountDownLatch wait_l; - - synchronized (this) { - wait_l = waitShutdown; - } - - Shutdown_ind = true; - - try { - if (wait_l != null) { - if (wait_l.await(3000, TimeUnit.MILLISECONDS)) - LOG.info("echo service shutdown complete"); - else - LOG.warn("timeout waiting for echo service shutdown"); - } else { - LOG.info("echo service shutdown: service does not appear to be active"); - } - } catch (InterruptedException int_exc) { - LOG.warn("interrupted while waiting for echo service shutdown"); - } - } - } - - /** - * - */ - protected class EchoRequestProcessor implements Runnable { - - protected Session session; - - protected Destination resp_dest; - protected MessageProducer msg_prod; - - protected Message request; - - public EchoRequestProcessor(Session sess, Message req) throws Exception { - this.session = sess; - this.request = req; - - this.resp_dest = req.getJMSReplyTo(); - - if (resp_dest == null) { - throw new Exception("invalid request: no reply-to destination given"); - } - - this.msg_prod = session.createProducer(this.resp_dest); - } - - @Override - public void run() { - try { - this.processRequest(this.request); - } catch (Exception ex) { - LOG.error("Failed to process request", ex); - } - } - - /** - * Process one request for the Echo Service. - */ - protected void processRequest(Message req) throws Exception { - if (LOG.isDebugEnabled()) - LOG.debug("ECHO request message " + req.toString()); - - resp_dest = req.getJMSReplyTo(); - if (resp_dest != null) { - msg_prod = session.createProducer(resp_dest); - - LOG.debug("SENDING ECHO RESPONSE to:" + resp_dest); - - msg_prod.send(req); - - LOG.debug((((ActiveMQSession) session).getConnection()).getBrokerName() + " SENT ECHO RESPONSE to " + resp_dest); - - msg_prod.close(); - msg_prod = null; - } else { - LOG.warn("invalid request: no reply-to destination given"); - } - } - } - - protected class TopicTrafficGenerator extends java.lang.Thread { - - protected Connection conn1; - protected Connection conn2; - protected Session sess1; - protected Session sess2; - protected Destination dest; - protected MessageProducer prod; - protected MessageConsumer cons; - protected boolean Shutdown_ind; - protected int send_count; - - public TopicTrafficGenerator(String url1, String url2) throws Exception { - conn1 = createConnection(url1); - conn2 = createConnection(url2); - - sess1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE); - sess2 = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); - - conn1.start(); - conn2.start(); - - dest = sess1.createTopic("traffic"); - prod = sess1.createProducer(dest); - - dest = sess2.createTopic("traffic"); - cons = sess2.createConsumer(dest); - } - - public void shutdown() { - Shutdown_ind = true; - } - - @Override - public void run() { - Message msg; - - try { - LOG.info("Starting Topic Traffic Generator"); - - while (!Shutdown_ind) { - msg = sess1.createTextMessage("TRAFFIC"); - - prod.send(msg); - - send_count++; - - // - // Time out the receipt; early messages may not make it. - // - - msg = cons.receive(250); - } - } catch (JMSException jms_exc) { - LOG.warn("traffic generator failed on jms exception", jms_exc); - } finally { - LOG.info("Shutdown of Topic Traffic Generator; send count = " + send_count); - - if (conn1 != null) { - try { - conn1.stop(); - } catch (JMSException jms_exc) { - LOG.warn("failed to shutdown connection", jms_exc); - } - } - - if (conn2 != null) { - try { - conn2.stop(); - } catch (JMSException jms_exc) { - LOG.warn("failed to shutdown connection", jms_exc); - } - } - } - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SingleBrokerVirtualDestinationsWithWildcardLevelDBTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SingleBrokerVirtualDestinationsWithWildcardLevelDBTest.java deleted file mode 100644 index 44faa19519..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SingleBrokerVirtualDestinationsWithWildcardLevelDBTest.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.activemq.usecases; - -import java.io.File; -import java.io.IOException; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.leveldb.LevelDBStore; - -public class SingleBrokerVirtualDestinationsWithWildcardLevelDBTest extends SingleBrokerVirtualDestinationsWithWildcardTest { - - @Override - protected void configurePersistenceAdapter(BrokerService broker) throws IOException { - File dataFileDir = new File("target/test-amq-data/leveldb/" + broker.getBrokerName()); - LevelDBStore kaha = new LevelDBStore(); - kaha.setDirectory(dataFileDir); - broker.setPersistenceAdapter(kaha); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SingleBrokerVirtualDestinationsWithWildcardTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SingleBrokerVirtualDestinationsWithWildcardTest.java deleted file mode 100644 index 37637f3671..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SingleBrokerVirtualDestinationsWithWildcardTest.java +++ /dev/null @@ -1,130 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.MessageConsumer; -import java.io.File; -import java.io.IOException; -import java.net.URI; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.DestinationInterceptor; -import org.apache.activemq.broker.region.virtual.VirtualDestination; -import org.apache.activemq.broker.region.virtual.VirtualDestinationInterceptor; -import org.apache.activemq.broker.region.virtual.VirtualTopic; -import org.apache.activemq.store.kahadb.KahaDBStore; -import org.apache.activemq.util.MessageIdList; - -public class SingleBrokerVirtualDestinationsWithWildcardTest extends JmsMultipleBrokersTestSupport { - - /** - * virtual destinations - */ - public void testVirtualDestinations() throws Exception { - startAllBrokers(); - - sendReceive("local.test", true, "Consumer.a.local.test", false, 1, 1); - sendReceive("global.test", true, "Consumer.a.global.test", false, 1, 1); - - destroyAllBrokers(); - } - - /** - * virtual destinations with wild-card subscriptions (without individual virtual queue) - */ - public void testVirtualDestinationsWithWildcardWithoutIndividualVirtualQueue() throws Exception { - startAllBrokers(); - - sendReceive("local.test.1", true, "Consumer.a.local.test.>", false, 1, 1); - sendReceive("global.test.1", true, "Consumer.a.global.test.>", false, 1, 1); - - destroyAllBrokers(); - } - - /** - * virtual destinations with wild-card subscriptions (with individual virtual queue) - */ - public void testVirtualDestinationsWithWildcardWithIndividualVirtualQueue() throws Exception { - startAllBrokers(); - - sendReceive("local.test.1", true, "Consumer.a.local.test.1", false, 1, 1); - sendReceive("local.test.1", true, "Consumer.a.local.test.>", false, 1, 1); - sendReceive("global.test.1", true, "Consumer.a.global.test.1", false, 1, 1); - sendReceive("global.test.1", true, "Consumer.a.global.test.>", false, 1, 1); - - destroyAllBrokers(); - } - - /** - * virtual destinations with wild-card subscriptions (wit virtual queue pre-created) - */ - public void testVirtualDestinationsWithWildcardWithVirtualQueuePreCreated() throws Exception { - startAllBrokers(); - - sendReceive("Consumer.a.local.test.>", false, "Consumer.a.local.test.>", false, 1, 1); - sendReceive("local.test.1", true, "Consumer.a.local.test.>", false, 1, 1); - sendReceive("Consumer.a.global.test.>", false, "Consumer.a.global.test.>", false, 1, 1); - sendReceive("global.test.1", true, "Consumer.a.global.test.>", false, 1, 1); - - destroyAllBrokers(); - } - - public void sendReceive(String dest1, - boolean topic1, - String dest2, - boolean topic2, - int send, - int expected) throws Exception { - MessageConsumer client = createConsumer("BrokerA", createDestination(dest2, topic2)); - Thread.sleep(1000); - sendMessages("BrokerA", createDestination(dest1, topic1), send); - MessageIdList msgs = getConsumerMessages("BrokerA", client); - msgs.setMaximumDuration(1000); - assertEquals(expected, msgs.getMessageCount()); - client.close(); - Thread.sleep(500); - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - String options = new String("?useJmx=false&deleteAllMessagesOnStartup=true"); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61616)/BrokerA" + options)); - } - - private BrokerService createAndConfigureBroker(URI uri) throws Exception { - BrokerService broker = createBroker(uri); - - configurePersistenceAdapter(broker); - - // make all topics virtual and consumers use the default prefix - VirtualDestinationInterceptor virtualDestinationInterceptor = new VirtualDestinationInterceptor(); - virtualDestinationInterceptor.setVirtualDestinations(new VirtualDestination[]{new VirtualTopic()}); - DestinationInterceptor[] destinationInterceptors = new DestinationInterceptor[]{virtualDestinationInterceptor}; - broker.setDestinationInterceptors(destinationInterceptors); - return broker; - } - - protected void configurePersistenceAdapter(BrokerService broker) throws IOException { - File dataFileDir = new File("target/test-amq-data/kahadb/" + broker.getBrokerName()); - KahaDBStore kaha = new KahaDBStore(); - kaha.setDirectory(dataFileDir); - broker.setPersistenceAdapter(kaha); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StartAndStopBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StartAndStopBrokerTest.java deleted file mode 100644 index 3da113229b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StartAndStopBrokerTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.JMSException; -import java.net.URI; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; - -/** - * @author Oliver Belikan - */ -public class StartAndStopBrokerTest extends TestCase { - - public void testStartupShutdown() throws Exception { - // This systemproperty is used if we dont want to - // have persistence messages as a default - System.setProperty("activemq.persistenceAdapter", "org.apache.activemq.store.vm.VMPersistenceAdapter"); - - // configuration of container and all protocols - BrokerService broker = createBroker(); - - // start a client - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:9100"); - factory.createConnection(); - - // stop activemq broker - broker.stop(); - - // start activemq broker again - broker = createBroker(); - - // start a client again - factory = new ActiveMQConnectionFactory("tcp://localhost:9100"); - factory.createConnection(); - - // stop activemq broker - broker.stop(); - - } - - protected BrokerService createBroker() throws JMSException { - BrokerService broker = null; - - try { - broker = BrokerFactory.createBroker(new URI("broker://()/localhost")); - broker.setBrokerName("DefaultBroker"); - broker.addConnector("tcp://localhost:9100"); - broker.setUseShutdownHook(false); - - broker.start(); - } catch (Exception e) { - e.printStackTrace(); - } - - return broker; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StartAndStopClientAndBrokerDoesNotLeaveThreadsRunningTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StartAndStopClientAndBrokerDoesNotLeaveThreadsRunningTest.java deleted file mode 100644 index b3a1449cfc..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StartAndStopClientAndBrokerDoesNotLeaveThreadsRunningTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; -import javax.jms.TextMessage; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.spring.ConsumerBean; - -/** - * - * - */ -public class StartAndStopClientAndBrokerDoesNotLeaveThreadsRunningTest extends TestCase { - - public static interface Task { - - void execute() throws Exception; - } - - @Override - public void setUp() throws Exception { - } - - public void testStartAndStopClientAndBrokerAndCheckNoThreadsAreLeft() throws Exception { - runTest(new Task() { - - @Override - public void execute() throws Exception { - BrokerService broker = new BrokerService(); - broker.setPersistent(false); - broker.start(); - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); - Connection connection = factory.createConnection(); - connection.start(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Queue destination = session.createQueue(getName()); - - // consumer - MessageConsumer consumer = session.createConsumer(destination); - ConsumerBean listener = new ConsumerBean(); - consumer.setMessageListener(listener); - - // producer - MessageProducer producer = session.createProducer(destination); - TextMessage message = session.createTextMessage("Hello World!"); - producer.send(message); - producer.close(); - - listener.assertMessagesArrived(1); - - consumer.close(); - session.close(); - connection.close(); - - broker.stop(); - } - }); - } - - public void runTest(Task task) throws Exception { - int before = Thread.currentThread().getThreadGroup().activeCount(); - - task.execute(); - - Thread.yield(); - // need to wait for slow servers - Thread.sleep(5000); - - int after = Thread.currentThread().getThreadGroup().activeCount(); - int diff = Math.abs(before - after); - assertTrue("Should be at most one more thread. Diff = " + diff, diff + 1 <= after); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StaticNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StaticNetworkTest.java deleted file mode 100644 index 57f271640b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/StaticNetworkTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.MessageConsumer; -import java.net.URI; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.util.MessageIdList; - -public class StaticNetworkTest extends JmsMultipleBrokersTestSupport { - - public void testStaticNetwork() throws Exception { - // Setup destination - ActiveMQDestination dest = createDestination("TEST", false); - ActiveMQDestination dest1 = createDestination("TEST1", false); - - NetworkConnector bridgeAB = bridgeBrokers("BrokerA", "BrokerB", true); - bridgeAB.addStaticallyIncludedDestination(dest); - bridgeAB.setStaticBridge(true); - - startAllBrokers(); - waitForBridgeFormation(); - - MessageConsumer consumer1 = createConsumer("BrokerB", dest); - MessageConsumer consumer2 = createConsumer("BrokerB", dest1); - - Thread.sleep(1000); - - sendMessages("BrokerA", dest, 1); - sendMessages("BrokerA", dest1, 1); - - MessageIdList msgs1 = getConsumerMessages("BrokerB", consumer1); - MessageIdList msgs2 = getConsumerMessages("BrokerB", consumer2); - - msgs1.waitForMessagesToArrive(1); - - Thread.sleep(1000); - - assertEquals(1, msgs1.getMessageCount()); - assertEquals(0, msgs2.getMessageCount()); - - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=false")); - createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=false")); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SubscribeClosePublishThenConsumeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SubscribeClosePublishThenConsumeTest.java deleted file mode 100644 index 0c86a1982c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/SubscribeClosePublishThenConsumeTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.Message; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.jms.Topic; -import javax.jms.TopicSubscriber; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.test.TestSupport; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Paul Smith - */ -public class SubscribeClosePublishThenConsumeTest extends TestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(SubscribeClosePublishThenConsumeTest.class); - - public void testDurableTopic() throws Exception { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://locahost"); - - String topicName = "TestTopic"; - String clientID = getName(); - String subscriberName = "MySubscriber:" + System.currentTimeMillis(); - - Connection connection = connectionFactory.createConnection(); - connection.setClientID(clientID); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - Topic topic = session.createTopic(topicName); - - // this should register a durable subscriber, we then close it to - // test that we get messages from the producer later on - TopicSubscriber subscriber = session.createDurableSubscriber(topic, subscriberName); - connection.start(); - - topic = null; - subscriber.close(); - subscriber = null; - session.close(); - session = null; - - // Create the new connection before closing to avoid the broker shutting - // down. - // now create a new Connection, Session & Producer, send some messages & - // then close - Connection t = connectionFactory.createConnection(); - connection.close(); - connection = t; - - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - topic = session.createTopic(topicName); - MessageProducer producer = session.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - TextMessage textMessage = session.createTextMessage("Hello World"); - producer.send(textMessage); - textMessage = null; - - topic = null; - session.close(); - session = null; - - // Now (re)register the Durable subscriber, setup a listener and wait - // for messages that should - // have been published by the previous producer - t = connectionFactory.createConnection(); - connection.close(); - connection = t; - - connection.setClientID(clientID); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - topic = session.createTopic(topicName); - - subscriber = session.createDurableSubscriber(topic, subscriberName); - connection.start(); - - LOG.info("Started connection - now about to try receive the textMessage"); - - long time = System.currentTimeMillis(); - Message message = subscriber.receive(15000L); - long elapsed = System.currentTimeMillis() - time; - - LOG.info("Waited for: " + elapsed + " millis"); - - assertNotNull("Should have received the message we published by now", message); - assertTrue("should be text textMessage", message instanceof TextMessage); - textMessage = (TextMessage) message; - assertEquals("Hello World", textMessage.getText()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TempTopicProducerFlowControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TempTopicProducerFlowControlTest.java deleted file mode 100644 index 5d9e481b03..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TempTopicProducerFlowControlTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Destination; -import javax.jms.Session; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; - -public class TempTopicProducerFlowControlTest extends TopicProducerFlowControlTest { - - @Override - protected void setDestinationPolicy(BrokerService broker, PolicyMap pm) { - PolicyEntry tpe = new PolicyEntry(); - tpe.setTempTopic(true); - tpe.setMemoryLimit(destinationMemLimit); - tpe.setProducerFlowControl(true); - tpe.setAdvisoryWhenFull(true); - pm.setDefaultEntry(tpe); - - broker.setDestinationPolicy(pm); - } - - @Override - protected Destination createDestination(Session session) throws Exception { - return session.createTemporaryTopic(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TestBrokerConnectionDuplexExcludedDestinations.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TestBrokerConnectionDuplexExcludedDestinations.java deleted file mode 100644 index 7f0dbacc0b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TestBrokerConnectionDuplexExcludedDestinations.java +++ /dev/null @@ -1,170 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.DeliveryMode; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.net.URI; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; - -public class TestBrokerConnectionDuplexExcludedDestinations extends TestCase { - - BrokerService receiverBroker; - BrokerService senderBroker; - - Connection hubConnection; - Session hubSession; - - Connection spokeConnection; - Session spokeSession; - - @Override - public void setUp() throws Exception { - // Hub broker - String configFileName = "org/apache/activemq/usecases/receiver-duplex.xml"; - URI uri = new URI("xbean:" + configFileName); - receiverBroker = BrokerFactory.createBroker(uri); - receiverBroker.setPersistent(false); - receiverBroker.setBrokerName("Hub"); - - // Spoke broker - configFileName = "org/apache/activemq/usecases/sender-duplex.xml"; - uri = new URI("xbean:" + configFileName); - senderBroker = BrokerFactory.createBroker(uri); - senderBroker.setPersistent(false); - senderBroker.setBrokerName("Spoke"); - - // Start both Hub and Spoke broker - receiverBroker.start(); - senderBroker.start(); - - // create hub session - ConnectionFactory cfHub = new ActiveMQConnectionFactory("tcp://localhost:62002"); - - hubConnection = cfHub.createConnection(); - hubConnection.start(); - hubSession = hubConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - // create spoke session - ConnectionFactory cfSpoke = new ActiveMQConnectionFactory("tcp://localhost:62001"); - spokeConnection = cfSpoke.createConnection(); - spokeConnection.start(); - spokeSession = spokeConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - } - - @Override - public void tearDown() throws Exception { - hubSession.close(); - hubConnection.stop(); - hubConnection.close(); - - spokeSession.close(); - spokeConnection.stop(); - spokeConnection.close(); - - senderBroker.stop(); - receiverBroker.stop(); - } - - public void testDuplexSendFromHubToSpoke() throws Exception { - - //create hub producer - MessageProducer hubProducer = hubSession.createProducer(null); - hubProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - hubProducer.setDisableMessageID(true); - hubProducer.setDisableMessageTimestamp(true); - - //create spoke producer - MessageProducer spokeProducer = hubSession.createProducer(null); - spokeProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - spokeProducer.setDisableMessageID(true); - spokeProducer.setDisableMessageTimestamp(true); - - Queue excludedQueueHub = hubSession.createQueue("exclude.test.foo"); - TextMessage excludedMsgHub = hubSession.createTextMessage(); - excludedMsgHub.setText(excludedQueueHub.toString()); - - Queue includedQueueHub = hubSession.createQueue("include.test.foo"); - - TextMessage includedMsgHub = hubSession.createTextMessage(); - includedMsgHub.setText(includedQueueHub.toString()); - - Queue alwaysIncludedQueueHub = hubSession.createQueue("always.include.test.foo"); - - TextMessage alwaysIncludedMsgHub = hubSession.createTextMessage(); - alwaysIncludedMsgHub.setText(alwaysIncludedQueueHub.toString()); - - // Sending from Hub queue - hubProducer.send(excludedQueueHub, excludedMsgHub); - hubProducer.send(includedQueueHub, includedMsgHub); - hubProducer.send(alwaysIncludedQueueHub, alwaysIncludedMsgHub); - - Queue excludedQueueSpoke = spokeSession.createQueue("exclude.test.foo"); - MessageConsumer excludedConsumerSpoke = spokeSession.createConsumer(excludedQueueSpoke); - - Thread.sleep(100); - - Queue includedQueueSpoke = spokeSession.createQueue("include.test.foo"); - MessageConsumer includedConsumerSpoke = spokeSession.createConsumer(includedQueueSpoke); - - Thread.sleep(100); - - Queue alwaysIncludedQueueSpoke = spokeSession.createQueue("always.include.test.foo"); - MessageConsumer alwaysIncludedConsumerSpoke = spokeSession.createConsumer(alwaysIncludedQueueHub); - - Thread.sleep(100); - TextMessage alwaysIncludedMsgSpoke = spokeSession.createTextMessage(); - alwaysIncludedMsgSpoke.setText(alwaysIncludedQueueSpoke.toString()); - spokeProducer.send(alwaysIncludedQueueSpoke, alwaysIncludedMsgSpoke); - - MessageConsumer alwaysIncludedConsumerHub = spokeSession.createConsumer(alwaysIncludedQueueHub); - assertNotNull(alwaysIncludedConsumerHub); - - // Receiving from excluded Spoke queue - Message msg = excludedConsumerSpoke.receive(200); - assertNull(msg); - - // Receiving from included Spoke queue - msg = includedConsumerSpoke.receive(200); - assertEquals(includedMsgHub, msg); - - // Receiving from included Spoke queue - msg = alwaysIncludedConsumerSpoke.receive(200); - assertEquals(alwaysIncludedMsgHub, msg); - - // we should be able to receive excluded queue message on Hub - MessageConsumer excludedConsumerHub = hubSession.createConsumer(excludedQueueHub); - msg = excludedConsumerHub.receive(200); - assertEquals(excludedMsgHub, msg); - - hubProducer.close(); - excludedConsumerSpoke.close(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TestSupport.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TestSupport.java deleted file mode 100644 index 184d0fb575..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TestSupport.java +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.TextMessage; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.command.ActiveMQMessage; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; - -/** - * Useful base class for unit test cases - */ -public class TestSupport extends TestCase { - - protected ActiveMQConnectionFactory connectionFactory; - protected boolean topic = true; - - public TestSupport() { - super(); - } - - public TestSupport(String name) { - super(name); - } - - protected ActiveMQMessage createMessage() { - return new ActiveMQMessage(); - } - - protected Destination createDestination(String subject) { - if (topic) { - return new ActiveMQTopic(subject); - } else { - return new ActiveMQQueue(subject); - } - } - - protected void assertTextMessagesEqual(Message[] firstSet, Message[] secondSet) throws JMSException { - assertTextMessagesEqual("", firstSet, secondSet); - } - - /** - * @param messsage - * @param firstSet - * @param secondSet - */ - protected void assertTextMessagesEqual(String messsage, - Message[] firstSet, - Message[] secondSet) throws JMSException { - assertEquals("Message count does not match: " + messsage, firstSet.length, secondSet.length); - for (int i = 0; i < secondSet.length; i++) { - TextMessage m1 = (TextMessage) firstSet[i]; - TextMessage m2 = (TextMessage) secondSet[i]; - assertTextMessageEqual("Message " + (i + 1) + " did not match : ", m1, m2); - } - } - - protected void assertEquals(TextMessage m1, TextMessage m2) throws JMSException { - assertEquals("", m1, m2); - } - - /** - * @param message - * @param firstSet - * @param secondSet - */ - protected void assertTextMessageEqual(String message, TextMessage m1, TextMessage m2) throws JMSException { - assertFalse(message + ": expected {" + m1 + "}, but was {" + m2 + "}", m1 == null ^ m2 == null); - if (m1 == null) { - return; - } - assertEquals(message, m1.getText(), m2.getText()); - } - - protected void assertEquals(Message m1, Message m2) throws JMSException { - assertEquals("", m1, m2); - } - - /** - * @param message - * @param firstSet - * @param secondSet - */ - protected void assertEquals(String message, Message m1, Message m2) throws JMSException { - assertFalse(message + ": expected {" + m1 + "}, but was {" + m2 + "}", m1 == null ^ m2 == null); - if (m1 == null) { - return; - } - assertTrue(message + ": expected {" + m1 + "}, but was {" + m2 + "}", m1.getClass() == m2.getClass()); - if (m1 instanceof TextMessage) { - assertTextMessageEqual(message, (TextMessage) m1, (TextMessage) m2); - } else { - assertEquals(message, m1, m2); - } - } - - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - return new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); - } - - /** - * Factory method to create a new connection - */ - protected Connection createConnection() throws Exception { - return getConnectionFactory().createConnection(); - } - - public ActiveMQConnectionFactory getConnectionFactory() throws Exception { - if (connectionFactory == null) { - connectionFactory = createConnectionFactory(); - assertTrue("Should have created a connection factory!", connectionFactory != null); - } - return connectionFactory; - } - - protected String getConsumerSubject() { - return getSubject(); - } - - protected String getProducerSubject() { - return getSubject(); - } - - protected String getSubject() { - return getClass().getName() + "." + getName(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerQueueNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerQueueNetworkTest.java deleted file mode 100644 index 6f3c80ff1f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerQueueNetworkTest.java +++ /dev/null @@ -1,668 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Destination; -import javax.jms.MessageConsumer; -import java.net.URI; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.Broker; -import org.apache.activemq.broker.BrokerFilter; -import org.apache.activemq.broker.BrokerPlugin; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.Queue; -import org.apache.activemq.broker.region.RegionBroker; -import org.apache.activemq.broker.region.Subscription; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ConsumerInfo; -import org.apache.activemq.command.MessageDispatch; -import org.apache.activemq.util.MessageIdList; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class ThreeBrokerQueueNetworkTest extends JmsMultipleBrokersTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(ThreeBrokerQueueNetworkTest.class); - protected static final int MESSAGE_COUNT = 100; - private static final long MAX_WAIT_MILLIS = 10000; - - interface Condition { - - boolean isSatisified() throws Exception; - } - - /** - * BrokerA -> BrokerB -> BrokerC - */ - public void testABandBCbrokerNetwork() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB"); - bridgeBrokers("BrokerB", "BrokerC"); - - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - MessageConsumer clientC = createConsumer("BrokerC", dest); - - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - - // Let's try to wait for any messages. Should be none. - Thread.sleep(1000); - - // Get message count - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - assertEquals(0, msgsC.getMessageCount()); - } - - /** - * BrokerA <- BrokerB -> BrokerC - */ - public void testBAandBCbrokerNetwork() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerB", "BrokerA"); - bridgeBrokers("BrokerB", "BrokerC"); - - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientC = createConsumer("BrokerC", dest); - Thread.sleep(2000); //et subscriptions get propagated - // Send messages - sendMessages("BrokerB", dest, MESSAGE_COUNT); - - // Let's try to wait for any messages. - Thread.sleep(1000); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - // Total received should be 100 - assertEquals(MESSAGE_COUNT, msgsA.getMessageCount() + msgsC.getMessageCount()); - } - - /** - * BrokerA <- BrokerB -> BrokerC - */ - public void testBAandBCbrokerNetworkWithSelectorsSendFirst() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerB", "BrokerA", true, 1, false); - bridgeBrokers("BrokerB", "BrokerC", true, 1, false); - - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Send messages for broker A - HashMap props = new HashMap<>(); - props.put("broker", "BROKER_A"); - sendMessages("BrokerB", dest, MESSAGE_COUNT, props); - - //Send messages for broker C - props.clear(); - props.put("broker", "BROKER_C"); - sendMessages("BrokerB", dest, MESSAGE_COUNT, props); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest, "broker = 'BROKER_A'"); - MessageConsumer clientC = createConsumer("BrokerC", dest, "broker = 'BROKER_C'"); - Thread.sleep(2000); //et subscriptions get propagated - - // Let's try to wait for any messages. - //Thread.sleep(1000); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - // Total received should be 100 - assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); - assertEquals(MESSAGE_COUNT, msgsC.getMessageCount()); - } - - /** - * BrokerA <- BrokerB -> BrokerC - */ - public void testBAandBCbrokerNetworkWithSelectorsSubscribeFirst() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerB", "BrokerA", true, 1, false); - bridgeBrokers("BrokerB", "BrokerC", true, 1, false); - - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest, "broker = 'BROKER_A'"); - MessageConsumer clientC = createConsumer("BrokerC", dest, "broker = 'BROKER_C'"); - Thread.sleep(2000); //et subscriptions get propagated - - // Send messages for broker A - HashMap props = new HashMap<>(); - props.put("broker", "BROKER_A"); - sendMessages("BrokerB", dest, MESSAGE_COUNT, props); - - //Send messages for broker C - props.clear(); - props.put("broker", "BROKER_C"); - sendMessages("BrokerB", dest, MESSAGE_COUNT, props); - - // Let's try to wait for any messages. - Thread.sleep(1000); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - // Total received should be 100 - assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); - assertEquals(MESSAGE_COUNT, msgsC.getMessageCount()); - } - - /** - * BrokerA -> BrokerB <- BrokerC - */ - public void testABandCBbrokerNetwork() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB"); - bridgeBrokers("BrokerC", "BrokerB"); - - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - MessageConsumer clientB = createConsumer("BrokerB", dest); - - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - sendMessages("BrokerC", dest, MESSAGE_COUNT); - - // Get message count - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - - msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 2); - - assertEquals(MESSAGE_COUNT * 2, msgsB.getMessageCount()); - } - - /** - * BrokerA <-> BrokerB <-> BrokerC - */ - public void testAllConnectedBrokerNetwork() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB"); - bridgeBrokers("BrokerB", "BrokerA"); - bridgeBrokers("BrokerB", "BrokerC"); - bridgeBrokers("BrokerC", "BrokerB"); - bridgeBrokers("BrokerA", "BrokerC"); - bridgeBrokers("BrokerC", "BrokerA"); - - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientB = createConsumer("BrokerB", dest); - MessageConsumer clientC = createConsumer("BrokerC", dest); - - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - sendMessages("BrokerB", dest, MESSAGE_COUNT); - sendMessages("BrokerC", dest, MESSAGE_COUNT); - - // Let's try to wait for any messages. - Thread.sleep(1000); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - assertEquals(MESSAGE_COUNT * 3, msgsA.getMessageCount() + msgsB.getMessageCount() + msgsC.getMessageCount()); - } - - public void testAllConnectedUsingMulticast() throws Exception { - // Setup broker networks - bridgeAllBrokers(); - - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientB = createConsumer("BrokerB", dest); - MessageConsumer clientC = createConsumer("BrokerC", dest); - - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - sendMessages("BrokerB", dest, MESSAGE_COUNT); - sendMessages("BrokerC", dest, MESSAGE_COUNT); - - // Let's try to wait for any messages. - Thread.sleep(1000); - - // Get message count - final MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - waitFor(new Condition() { - @Override - public boolean isSatisified() { - return msgsA.getMessageCount() == MESSAGE_COUNT; - } - }); - - assertEquals(MESSAGE_COUNT * 3, msgsA.getMessageCount() + msgsB.getMessageCount() + msgsC.getMessageCount()); - } - - // on slow machines some more waiting is required on account of slow advisories - private void waitFor(Condition condition) throws Exception { - final long expiry = System.currentTimeMillis() + MAX_WAIT_MILLIS; - while (!condition.isSatisified() && System.currentTimeMillis() < expiry) { - Thread.sleep(1000); - } - if (System.currentTimeMillis() >= expiry) { - LOG.error("expired while waiting for condition " + condition); - } - - } - - public void testAllConnectedUsingMulticastProducerConsumerOnA() throws Exception { - bridgeAllBrokers("default", 3, false); - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - int messageCount = 2000; - CountDownLatch messagesReceived = new CountDownLatch(messageCount); - MessageConsumer clientA = createConsumer("BrokerA", dest, messagesReceived); - - // Let's try to wait for advisory percolation. - Thread.sleep(1000); - - // Send messages - sendMessages("BrokerA", dest, messageCount); - - assertTrue(messagesReceived.await(30, TimeUnit.SECONDS)); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - assertEquals(messageCount, msgsA.getMessageCount()); - } - - public void testAllConnectedWithSpare() throws Exception { - bridgeAllBrokers("default", 3, false); - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - int messageCount = 2000; - CountDownLatch messagesReceived = new CountDownLatch(messageCount); - MessageConsumer clientA = createConsumer("BrokerA", dest, messagesReceived); - - // ensure advisory percolation. - Thread.sleep(2000); - - // Send messages - sendMessages("BrokerB", dest, messageCount); - - assertTrue("messaged received within time limit", messagesReceived.await(30, TimeUnit.SECONDS)); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - assertEquals(messageCount, msgsA.getMessageCount()); - } - - /* - * This test is disabled - as it fails with a fix for - * http://issues.apache.org/activemq/browse/AMQ-2530 - which highlights that - * For a Conduit bridge - local subscription Ids weren't removed in a ConduitBridge - * The test fails because on closing clientA - clientB correctly receives all the - * messages - ie. half dont get stuck on BrokerA - - */ - public void XtestMigrateConsumerStuckMessages() throws Exception { - boolean suppressQueueDuplicateSubscriptions = false; - bridgeAllBrokers("default", 3, suppressQueueDuplicateSubscriptions); - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - LOG.info("Consumer on A"); - MessageConsumer clientA = createConsumer("BrokerA", dest); - - // ensure advisors have percolated - Thread.sleep(2000); - - LOG.info("Consumer on B"); - int messageCount = 2000; - - // will only get half of the messages - CountDownLatch messagesReceived = new CountDownLatch(messageCount / 2); - MessageConsumer clientB = createConsumer("BrokerB", dest, messagesReceived); - - // ensure advisors have percolated - Thread.sleep(2000); - - LOG.info("Close consumer on A"); - clientA.close(); - - // ensure advisors have percolated - Thread.sleep(2000); - - LOG.info("Send to B"); - sendMessages("BrokerB", dest, messageCount); - - // Let's try to wait for any messages. - assertTrue(messagesReceived.await(30, TimeUnit.SECONDS)); - - // Get message count - MessageIdList msgs = getConsumerMessages("BrokerB", clientB); - - // see will any more arrive - Thread.sleep(500); - assertEquals(messageCount / 2, msgs.getMessageCount()); - - // pick up the stuck messages - messagesReceived = new CountDownLatch(messageCount / 2); - clientA = createConsumer("BrokerA", dest, messagesReceived); - // Let's try to wait for any messages. - assertTrue(messagesReceived.await(30, TimeUnit.SECONDS)); - - msgs = getConsumerMessages("BrokerA", clientA); - assertEquals(messageCount / 2, msgs.getMessageCount()); - } - - // use case: for maintenance, migrate consumers and producers from one - // node in the network to another so node can be replaced/updated - public void testMigrateConsumer() throws Exception { - boolean suppressQueueDuplicateSubscriptions = true; - boolean decreaseNetworkConsumerPriority = true; - bridgeAllBrokers("default", 3, suppressQueueDuplicateSubscriptions, decreaseNetworkConsumerPriority); - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - LOG.info("Consumer on A"); - MessageConsumer clientA = createConsumer("BrokerA", dest); - - // ensure advisors have percolated - Thread.sleep(2000); - - LOG.info("Consumer on B"); - int messageCount = 2000; - CountDownLatch messagesReceived = new CountDownLatch(messageCount); - MessageConsumer clientB = createConsumer("BrokerB", dest, messagesReceived); - - // make the consumer slow so that any network consumer has a chance, even - // if it has a lower priority - MessageIdList msgs = getConsumerMessages("BrokerB", clientB); - msgs.setProcessingDelay(10); - - // ensure advisors have percolated - Thread.sleep(2000); - - LOG.info("Close consumer on A"); - clientA.close(); - - // ensure advisors have percolated - Thread.sleep(2000); - - LOG.info("Send to B"); - sendMessages("BrokerB", dest, messageCount); - - // Let's try to wait for any messages. - assertTrue("messages are received within limit", messagesReceived.await(60, TimeUnit.SECONDS)); - assertEquals(messageCount, msgs.getMessageCount()); - } - - public void testNoDuplicateQueueSubs() throws Exception { - - bridgeAllBrokers("default", 3, true); - - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - String brokerName = "BrokerA"; - MessageConsumer consumer = createConsumer(brokerName, dest); - - // wait for advisories - Thread.sleep(2000); - - // verify there is one consumer on each broker, no cycles - Collection brokerList = brokers.values(); - for (Iterator i = brokerList.iterator(); i.hasNext(); ) { - BrokerService broker = i.next().broker; - verifyConsumerCount(broker, 1, dest); - } - - consumer.close(); - - // wait for advisories - Thread.sleep(2000); - - // verify there is no more consumers - for (Iterator i = brokerList.iterator(); i.hasNext(); ) { - BrokerService broker = i.next().broker; - verifyConsumerCount(broker, 0, dest); - } - } - - public void testNoDuplicateQueueSubsHasLowestPriority() throws Exception { - boolean suppressQueueDuplicateSubscriptions = true; - boolean decreaseNetworkConsumerPriority = true; - bridgeAllBrokers("default", 3, suppressQueueDuplicateSubscriptions, decreaseNetworkConsumerPriority); - - // Setup destination - final Destination dest = createDestination("TEST.FOO", false); - - // delay the advisory messages so that one can percolate fully (cyclically) before the other - BrokerItem brokerB = brokers.get("BrokerA"); - brokerB.broker.setPlugins(new BrokerPlugin[]{new BrokerPlugin() { - - @Override - public Broker installPlugin(Broker broker) throws Exception { - return new BrokerFilter(broker) { - - final AtomicInteger count = new AtomicInteger(); - - @Override - public void preProcessDispatch(MessageDispatch messageDispatch) { - if (messageDispatch.getDestination().getPhysicalName().contains("ActiveMQ.Advisory.Consumer")) { - // lets delay the first advisory - if (count.getAndIncrement() == 0) { - LOG.info("Sleeping on first advisory: " + messageDispatch); - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - super.postProcessDispatch(messageDispatch); - } - - }; - } - }}); - - startAllBrokers(); - waitForBridgeFormation(); - - // Setup consumers - String brokerName = "BrokerA"; - createConsumer(brokerName, dest); - - // wait for advisories - Thread.sleep(5000); - - // verify there is one consumer on each broker, no cycles - Collection brokerList = brokers.values(); - for (Iterator i = brokerList.iterator(); i.hasNext(); ) { - BrokerService broker = i.next().broker; - verifyConsumerCount(broker, 1, dest); - if (!brokerName.equals(broker.getBrokerName())) { - verifyConsumePriority(broker, ConsumerInfo.NETWORK_CONSUMER_PRIORITY, dest); - } - } - } - - public void testDuplicateQueueSubs() throws Exception { - - configureBroker(createBroker("BrokerD")); - - bridgeAllBrokers("default", 3, false); - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - String brokerName = "BrokerA"; - MessageConsumer consumer = createConsumer(brokerName, dest); - - // wait for advisories - Thread.sleep(2000); - - verifyConsumerCount(brokers.get(brokerName).broker, 1, dest); - - // in a cyclic network, other brokers will get second order consumer - // an alternative route to A via each other - Collection brokerList = brokers.values(); - for (Iterator i = brokerList.iterator(); i.hasNext(); ) { - BrokerService broker = i.next().broker; - if (!brokerName.equals(broker.getBrokerName())) { - verifyConsumerCount(broker, 5, dest); - verifyConsumePriority(broker, ConsumerInfo.NORMAL_PRIORITY, dest); - } - } - - consumer.close(); - - // wait for advisories - Thread.sleep(2000); - - for (Iterator i = brokerList.iterator(); i.hasNext(); ) { - BrokerService broker = i.next().broker; - if (!brokerName.equals(broker.getBrokerName())) { - logConsumerCount(broker, 0, dest); - } - } - - for (Iterator i = brokerList.iterator(); i.hasNext(); ) { - BrokerService broker = i.next().broker; - verifyConsumerCount(broker, 0, dest); - } - } - - private void verifyConsumerCount(BrokerService broker, int count, final Destination dest) throws Exception { - final RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); - waitFor(new Condition() { - @Override - public boolean isSatisified() throws Exception { - return !regionBroker.getDestinations(ActiveMQDestination.transform(dest)).isEmpty(); - } - }); - Queue internalQueue = (Queue) regionBroker.getDestinations(ActiveMQDestination.transform(dest)).iterator().next(); - LOG.info("Verify: consumer count on " + broker.getBrokerName() + " matches:" + count + ", val:" + internalQueue.getConsumers().size()); - assertEquals("consumer count on " + broker.getBrokerName() + " matches for q: " + internalQueue, count, internalQueue.getConsumers().size()); - } - - private void logConsumerCount(BrokerService broker, int count, final Destination dest) throws Exception { - final RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); - waitFor(new Condition() { - @Override - public boolean isSatisified() throws Exception { - return !regionBroker.getDestinations(ActiveMQDestination.transform(dest)).isEmpty(); - } - }); - Queue internalQueue = (Queue) regionBroker.getDestinations(ActiveMQDestination.transform(dest)).iterator().next(); - LOG.info("Verify: consumer count on " + broker.getBrokerName() + " matches:" + count + ", val:" + internalQueue.getConsumers().size()); - } - - private void verifyConsumePriority(BrokerService broker, byte expectedPriority, Destination dest) throws Exception { - RegionBroker regionBroker = (RegionBroker) broker.getRegionBroker(); - Queue internalQueue = (Queue) regionBroker.getDestinations(ActiveMQDestination.transform(dest)).iterator().next(); - for (Subscription consumer : internalQueue.getConsumers()) { - assertEquals("consumer on " + broker.getBrokerName() + " matches priority: " + internalQueue, expectedPriority, consumer.getConsumerInfo().getPriority()); - } - } - - @Override - public void configureBroker(BrokerService brokerService) { - brokerService.setBrokerId(brokerService.getBrokerName()); - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=false")); - createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=false")); - createBroker(new URI("broker:(tcp://localhost:61618)/BrokerC?persistent=false&useJmx=false")); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerQueueNetworkUsingTcpTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerQueueNetworkUsingTcpTest.java deleted file mode 100644 index effe0da115..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerQueueNetworkUsingTcpTest.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.activemq.usecases; - -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.network.DemandForwardingBridge; -import org.apache.activemq.network.NetworkBridgeConfiguration; -import org.apache.activemq.transport.TransportFactory; - -/** - * - */ -public class ThreeBrokerQueueNetworkUsingTcpTest extends ThreeBrokerQueueNetworkTest { - - protected List bridges; - - protected void bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker) throws Exception { - List remoteTransports = remoteBroker.getTransportConnectors(); - List localTransports = localBroker.getTransportConnectors(); - - URI remoteURI; - URI localURI; - if (!remoteTransports.isEmpty() && !localTransports.isEmpty()) { - remoteURI = remoteTransports.get(0).getConnectUri(); - localURI = localTransports.get(0).getConnectUri(); - - // Ensure that we are connecting using tcp - if (remoteURI.toString().startsWith("tcp:") && localURI.toString().startsWith("tcp:")) { - NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); - config.setBrokerName(localBroker.getBrokerName()); - DemandForwardingBridge bridge = new DemandForwardingBridge(config, TransportFactory.connect(localURI), TransportFactory.connect(remoteURI)); - bridge.setBrokerService(localBroker); - bridges.add(bridge); - - bridge.start(); - } else { - throw new Exception("Remote broker or local broker is not using tcp connectors"); - } - } else { - throw new Exception("Remote broker or local broker has no registered connectors."); - } - - maxSetupTime = 2000; - } - - @Override - public void setUp() throws Exception { - super.setUp(); - - bridges = new ArrayList<>(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerStompTemporaryQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerStompTemporaryQueueTest.java deleted file mode 100644 index daac41a627..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerStompTemporaryQueueTest.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.activemq.usecases; - -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.util.List; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.network.DiscoveryNetworkConnector; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.store.kahadb.KahaDBStore; -import org.apache.activemq.transport.stomp.Stomp; -import org.apache.activemq.transport.stomp.StompConnection; -import org.apache.activemq.transport.stomp.StompFrame; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ThreeBrokerStompTemporaryQueueTest extends JmsMultipleBrokersTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(ThreeBrokerStompTemporaryQueueTest.class); - private StompConnection stompConnection; - - @Override - protected NetworkConnector bridgeBrokers(BrokerService localBroker, - BrokerService remoteBroker, - boolean dynamicOnly, - int networkTTL, - boolean conduit, - boolean failover) throws Exception { - List transportConnectors = remoteBroker.getTransportConnectors(); - URI remoteURI; - if (!transportConnectors.isEmpty()) { - remoteURI = transportConnectors.get(0).getConnectUri(); - NetworkConnector connector = new DiscoveryNetworkConnector(new URI("static:" + remoteURI)); - connector.setName(localBroker.getBrokerName() + remoteBroker.getBrokerName()); - localBroker.addNetworkConnector(connector); - maxSetupTime = 2000; - return connector; - } else { - throw new Exception("Remote broker has no registered connectors."); - } - } - - public void testStompTemporaryQueue() throws Exception { - // Setup broker networks - bridgeAndConfigureBrokers("BrokerA", "BrokerB"); - bridgeAndConfigureBrokers("BrokerA", "BrokerC"); - bridgeAndConfigureBrokers("BrokerB", "BrokerA"); - bridgeAndConfigureBrokers("BrokerB", "BrokerC"); - bridgeAndConfigureBrokers("BrokerC", "BrokerA"); - bridgeAndConfigureBrokers("BrokerC", "BrokerB"); - - startAllBrokers(); - waitForBridgeFormation(); - - Thread.sleep(1000); - - stompConnection = new StompConnection(); - stompConnection.open("localhost", 61614); - // Creating a temp queue - stompConnection.sendFrame("CONNECT\n" + "login:system\n" + "passcode:manager\n\n" + Stomp.NULL); - - StompFrame frame = stompConnection.receive(); - assertTrue(frame.toString().startsWith("CONNECTED")); - - stompConnection.subscribe("/temp-queue/meaningless", "auto"); - stompConnection.send("/temp-queue/meaningless", "Hello World"); - - frame = stompConnection.receive(3000); - assertEquals("Hello World", frame.getBody()); - - Thread.sleep(1000); - - assertEquals("Destination", 1, brokers.get("BrokerA").broker.getAdminView().getTemporaryQueues().length); - assertEquals("Destination", 1, brokers.get("BrokerB").broker.getAdminView().getTemporaryQueues().length); - assertEquals("Destination", 1, brokers.get("BrokerC").broker.getAdminView().getTemporaryQueues().length); - - int advisoryTopicsForTempQueues; - advisoryTopicsForTempQueues = countTopicsByName("BrokerA", "ActiveMQ.Advisory.Consumer.Queue.ID"); - assertEquals("Advisory topic should be present", 1, advisoryTopicsForTempQueues); - - advisoryTopicsForTempQueues = countTopicsByName("BrokerB", "ActiveMQ.Advisory.Consumer.Queue.ID"); - assertEquals("Advisory topic should be present", 1, advisoryTopicsForTempQueues); - - advisoryTopicsForTempQueues = countTopicsByName("BrokerC", "ActiveMQ.Advisory.Consumer.Queue.ID"); - assertEquals("Advisory topic should be present", 1, advisoryTopicsForTempQueues); - - stompConnection.disconnect(); - - Thread.sleep(1000); - - advisoryTopicsForTempQueues = countTopicsByName("BrokerA", "ActiveMQ.Advisory.Consumer.Queue.ID"); - assertEquals("Advisory topic should have been deleted", 0, advisoryTopicsForTempQueues); - advisoryTopicsForTempQueues = countTopicsByName("BrokerB", "ActiveMQ.Advisory.Consumer.Queue.ID"); - assertEquals("Advisory topic should have been deleted", 0, advisoryTopicsForTempQueues); - advisoryTopicsForTempQueues = countTopicsByName("BrokerC", "ActiveMQ.Advisory.Consumer.Queue.ID"); - assertEquals("Advisory topic should have been deleted", 0, advisoryTopicsForTempQueues); - - LOG.info("Restarting brokerA"); - BrokerItem brokerItem = brokers.remove("BrokerA"); - if (brokerItem != null) { - brokerItem.destroy(); - } - - BrokerService restartedBroker = createAndConfigureBroker(new URI("broker:(tcp://localhost:61616,stomp://localhost:61613)/BrokerA")); - bridgeAndConfigureBrokers("BrokerA", "BrokerB"); - bridgeAndConfigureBrokers("BrokerA", "BrokerC"); - restartedBroker.start(); - waitForBridgeFormation(); - - Thread.sleep(3000); - - assertEquals("Destination", 0, brokers.get("BrokerA").broker.getAdminView().getTemporaryQueues().length); - assertEquals("Destination", 0, brokers.get("BrokerB").broker.getAdminView().getTemporaryQueues().length); - assertEquals("Destination", 0, brokers.get("BrokerC").broker.getAdminView().getTemporaryQueues().length); - - advisoryTopicsForTempQueues = countTopicsByName("BrokerA", "ActiveMQ.Advisory.Consumer.Queue.ID"); - assertEquals("Advisory topic should have been deleted", 0, advisoryTopicsForTempQueues); - advisoryTopicsForTempQueues = countTopicsByName("BrokerB", "ActiveMQ.Advisory.Consumer.Queue.ID"); - assertEquals("Advisory topic should have been deleted", 0, advisoryTopicsForTempQueues); - advisoryTopicsForTempQueues = countTopicsByName("BrokerC", "ActiveMQ.Advisory.Consumer.Queue.ID"); - assertEquals("Advisory topic should have been deleted", 0, advisoryTopicsForTempQueues); - } - - private int countTopicsByName(String broker, String name) throws Exception { - int advisoryTopicsForTempQueues = 0; - for (int i = 0; i < brokers.get(broker).broker.getAdminView().getTopics().length; i++) { - if (brokers.get(broker).broker.getAdminView().getTopics()[i].toString().contains(name)) { - advisoryTopicsForTempQueues++; - } - } - return advisoryTopicsForTempQueues; - } - - private void bridgeAndConfigureBrokers(String local, String remote) throws Exception { - NetworkConnector bridge = bridgeBrokers(local, remote); - assertNotNull(bridge); - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - String options = new String("?deleteAllMessagesOnStartup=true"); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61616,stomp://localhost:61613)/BrokerA" + options)); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61617,stomp://localhost:61614)/BrokerB" + options)); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61618,stomp://localhost:61615)/BrokerC" + options)); - } - - private BrokerService createAndConfigureBroker(URI uri) throws Exception { - BrokerService broker = createBroker(uri); - configurePersistenceAdapter(broker); - return broker; - } - - protected void configurePersistenceAdapter(BrokerService broker) throws IOException { - File dataFileDir = new File("target/test-amq-data/kahadb/" + broker.getBrokerName()); - KahaDBStore kaha = new KahaDBStore(); - kaha.setDirectory(dataFileDir); - broker.setPersistenceAdapter(kaha); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTempDestDemandSubscriptionCleanupTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTempDestDemandSubscriptionCleanupTest.java deleted file mode 100644 index 09471339e2..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTempDestDemandSubscriptionCleanupTest.java +++ /dev/null @@ -1,262 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.net.URI; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.region.AbstractRegion; -import org.apache.activemq.broker.region.RegionBroker; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.util.Wait; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Christian Posta - */ -public class ThreeBrokerTempDestDemandSubscriptionCleanupTest extends JmsMultipleBrokersTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(ThreeBrokerTempDestDemandSubscriptionCleanupTest.class); - - boolean enableTempDestinationBridging = true; - - private static final String BROKER_A = "BrokerA"; - private static final String BROKER_B = "BrokerB"; - private static final String BROKER_C = "BrokerC"; - - private static final String ECHO_QUEUE_NAME = "echo"; - private static final int NUM_ITER = 100; - private static final long CONSUME_TIMEOUT = 500; - - /** - * So we network three brokers together, and send a message with request-reply semantics. - * The message goes to an echo service listening on broker C. We send a message on a queue - * to broker A which gets demand forwarded to broker C. the echo service will respond to the - * temp destination listed in the JMSReplyTo header. that will get demand forwarded back to - * broker A. When the consumer of the temp dest on broker A closes, that subscription should - * be removed on broker A. advisories firing from broker A to broker B should remove that - * subscription on broker B. advisories firing from broker B to broker C should remove that - * subscription on broker C. - * - * @throws Exception - */ - public void testSubscriptionsCleanedUpRace() throws Exception { - - final BrokerItem brokerA = brokers.get(BROKER_A); - - Runnable tester = new Runnable() { - - @Override - public void run() { - for (int i = 0; i < NUM_ITER; i++) { - - Connection conn = null; - try { - conn = brokerA.createConnection(); - - conn.start(); - - final Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = sess.createQueue(ECHO_QUEUE_NAME); - - MessageProducer producer = sess.createProducer(destination); - - LOG.info("Starting iter: " + i); - Destination replyTo = sess.createTemporaryQueue(); - MessageConsumer responseConsumer = sess.createConsumer(replyTo); - - Message message = sess.createTextMessage("Iteration: " + i); - message.setJMSReplyTo(replyTo); - - producer.send(message); - - TextMessage response = (TextMessage) responseConsumer.receive(CONSUME_TIMEOUT); - assertNotNull("We should have gotten a response, but didn't for iter: " + i, response); - assertEquals("We got the wrong response from the echo service", "Iteration: " + i, response.getText()); - - // so we close the consumer so that an actual RemoveInfo command gets propagated through the - // network - responseConsumer.close(); - conn.close(); - - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - - } - } - }; - - ExecutorService threadService = Executors.newFixedThreadPool(2); - threadService.submit(tester); - threadService.submit(tester); - - threadService.shutdown(); - assertTrue("executor done on time", threadService.awaitTermination(30L, TimeUnit.SECONDS)); - - // for the real test... we should not have any subscriptions left on broker C for the temp dests - BrokerItem brokerC = brokers.get(BROKER_C); - RegionBroker regionBroker = (RegionBroker) brokerC.broker.getRegionBroker(); - final AbstractRegion region = (AbstractRegion) regionBroker.getTempQueueRegion(); - - assertTrue("There were no lingering temp-queue destinations", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Lingering temps: " + region.getSubscriptions().size()); - return 0 == region.getSubscriptions().size(); - } - })); - } - - /** - * This test is slightly different from the above. We don't explicitly close the consumer down - * (which we did in the previous test to force the RemoveInfo to be sent). Here we just close - * the connection which should still clean up the subscriptions and temp destinations on the - * networked brokers. - * - * @throws Exception - */ - public void testSubscriptionsCleanedUpAfterConnectionClose() throws Exception { - - final BrokerItem brokerA = brokers.get(BROKER_A); - - for (int i = 0; i < NUM_ITER; i++) { - - Connection conn = null; - try { - conn = brokerA.createConnection(); - - conn.start(); - - final Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = sess.createQueue(ECHO_QUEUE_NAME); - - MessageProducer producer = sess.createProducer(destination); - - LOG.info("Starting iter: " + i); - Destination replyTo = sess.createTemporaryQueue(); - MessageConsumer responseConsumer = sess.createConsumer(replyTo); - - Message message = sess.createTextMessage("Iteration: " + i); - message.setJMSReplyTo(replyTo); - - producer.send(message); - - TextMessage response = (TextMessage) responseConsumer.receive(CONSUME_TIMEOUT); - assertNotNull("We should have gotten a response, but didn't for iter: " + i, response); - assertEquals("We got the wrong response from the echo service", "Iteration: " + i, response.getText()); - - // so closing the connection without closing the consumer first will leak subscriptions - // in a nob? - // responseConsumer.close(); - conn.close(); - - } catch (Exception e) { - e.printStackTrace(); - fail(); - } - - } - - // for the real test... we should not have any subscriptions left on broker C for the temp dests - BrokerItem brokerC = brokers.get(BROKER_C); - RegionBroker regionBroker = (RegionBroker) brokerC.broker.getRegionBroker(); - final AbstractRegion region = (AbstractRegion) regionBroker.getTempQueueRegion(); - - assertTrue("There were no lingering temp-queue destinations", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Lingering temps: " + region.getSubscriptions().size()); - return 0 == region.getSubscriptions().size(); - } - })); - - } - - private void installEchoClientOnBrokerC() throws Exception { - BrokerItem brokerC = brokers.get(BROKER_C); - Connection conn = brokerC.createConnection(); - conn.start(); - - final Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = sess.createQueue(ECHO_QUEUE_NAME); - MessageConsumer consumer = sess.createConsumer(destination); - - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - - TextMessage textMessage = (TextMessage) message; - - try { - Destination replyTo = message.getJMSReplyTo(); - - MessageProducer producer = sess.createProducer(replyTo); - Message response = sess.createTextMessage(textMessage.getText()); - - LOG.info("Replying to this request: " + textMessage.getText()); - producer.send(response); - producer.close(); - - } catch (JMSException e) { - e.printStackTrace(); - fail("Could not respond to an echo request"); - } - } - }); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - createBroker(new URI("broker:(tcp://localhost:61616)/" + BROKER_A + "?persistent=false&useJmx=false")); - createBroker(new URI("broker:(tcp://localhost:61617)/" + BROKER_B + "?persistent=false&useJmx=false")); - createBroker(new URI("broker:(tcp://localhost:61618)/" + BROKER_C + "?persistent=false&useJmx=false")); - - bridgeBrokers("BrokerA", "BrokerB", false, 3); - bridgeBrokers("BrokerB", "BrokerC", false, 3); - - startAllBrokers(); - - // set up a listener on broker C that will demand forward subscriptions over the network - installEchoClientOnBrokerC(); - } - - protected NetworkConnector bridgeBrokers(String localBrokerName, - String remoteBrokerName, - boolean dynamicOnly, - int networkTTL) throws Exception { - NetworkConnector connector = super.bridgeBrokers(localBrokerName, remoteBrokerName, dynamicOnly, networkTTL, true); - connector.setBridgeTempDestinations(enableTempDestinationBridging); - connector.setDuplex(true); - return connector; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTempQueueNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTempQueueNetworkTest.java deleted file mode 100644 index aa6a139c8a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTempQueueNetworkTest.java +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Session; -import javax.jms.TemporaryQueue; -import java.net.URI; -import java.util.Iterator; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.network.NetworkConnector; - -/** - * - */ -public class ThreeBrokerTempQueueNetworkTest extends JmsMultipleBrokersTestSupport { - - protected static final int MESSAGE_COUNT = 100; - boolean enableTempDestinationBridging = true; - - /** - * BrokerA -> BrokerB -> BrokerC - */ - public void testTempQueueCleanup() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB", false, 2); - bridgeBrokers("BrokerB", "BrokerC", false, 2); - startAllBrokers(); - BrokerItem brokerItem = brokers.get("BrokerC"); - Connection conn = brokerItem.createConnection(); - conn.start(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - TemporaryQueue tempQ = sess.createTemporaryQueue(); - Thread.sleep(5000); - for (Iterator i = brokers.values().iterator(); i.hasNext(); ) { - BrokerItem bi = i.next(); - assertEquals("No queues on broker " + bi.broker.getBrokerName(), 1, bi.broker.getAdminView().getTemporaryQueues().length); - } - tempQ.delete(); - Thread.sleep(2000); - for (Iterator i = brokers.values().iterator(); i.hasNext(); ) { - BrokerItem bi = i.next(); - assertEquals("Temp queue left behind on broker " + bi.broker.getBrokerName(), 0, bi.broker.getAdminView().getTemporaryQueues().length); - } - } - - // this actually uses 4 brokers ... - public void testTempQueueRecovery() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB", false, 3); - bridgeBrokers("BrokerB", "BrokerC", false, 3); - startAllBrokers(); - BrokerItem brokerItem = brokers.get("BrokerC"); - Connection conn = brokerItem.createConnection(); - conn.start(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - TemporaryQueue tempQ = sess.createTemporaryQueue(); - Thread.sleep(5000); - for (Iterator i = brokers.values().iterator(); i.hasNext(); ) { - BrokerItem bi = i.next(); - assertEquals("No queues on broker " + bi.broker.getBrokerName(), 1, bi.broker.getAdminView().getTemporaryQueues().length); - } - createBroker(new URI("broker:(tcp://localhost:61619)/BrokerD?persistent=false&useJmx=true")); - bridgeBrokers("BrokerD", "BrokerA", false, 3); - BrokerItem newBroker = brokers.get("BrokerD"); - newBroker.broker.start(); - Thread.sleep(1000); - assertEquals("No queues on broker D", 1, newBroker.broker.getAdminView().getTemporaryQueues().length); - tempQ.delete(); - Thread.sleep(2000); - for (Iterator i = brokers.values().iterator(); i.hasNext(); ) { - BrokerItem bi = i.next(); - assertEquals("Temp queue left behind on broker " + bi.broker.getBrokerName(), 0, bi.broker.getAdminView().getTemporaryQueues().length); - } - } - - public void testTempDisable() throws Exception { - enableTempDestinationBridging = false; - try { - testTempQueueCleanup(); - } catch (Throwable e) { - // Expecting an error - return; - } - fail("Test should have failed since temp queues are disabled."); - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=true")); - createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=true")); - createBroker(new URI("broker:(tcp://localhost:61618)/BrokerC?persistent=false&useJmx=true")); - } - - protected NetworkConnector bridgeBrokers(String localBrokerName, - String remoteBrokerName, - boolean dynamicOnly, - int networkTTL) throws Exception { - NetworkConnector connector = super.bridgeBrokers(localBrokerName, remoteBrokerName, dynamicOnly, networkTTL, true); - connector.setBridgeTempDestinations(enableTempDestinationBridging); - return connector; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTopicNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTopicNetworkTest.java deleted file mode 100644 index b61186f7b3..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTopicNetworkTest.java +++ /dev/null @@ -1,410 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Destination; -import javax.jms.MessageConsumer; -import javax.jms.Topic; -import java.net.URI; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; - -import junit.framework.Test; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.util.MessageIdList; - -/** - * - */ -public class ThreeBrokerTopicNetworkTest extends JmsMultipleBrokersTestSupport { - - protected static final int MESSAGE_COUNT = 100; - public boolean dynamicOnly; - - /** - * BrokerA -> BrokerB -> BrokerC - */ - public void testABandBCbrokerNetwork() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB"); - bridgeBrokers("BrokerB", "BrokerC"); - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", true); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientB = createConsumer("BrokerB", dest); - MessageConsumer clientC = createConsumer("BrokerC", dest); - - //let consumers propagate around the network - Thread.sleep(2000); - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - sendMessages("BrokerB", dest, MESSAGE_COUNT); - sendMessages("BrokerC", dest, MESSAGE_COUNT); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - msgsA.waitForMessagesToArrive(MESSAGE_COUNT); - msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 2); - msgsC.waitForMessagesToArrive(MESSAGE_COUNT * 2); - - assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); - assertEquals(MESSAGE_COUNT * 2, msgsB.getMessageCount()); - assertEquals(MESSAGE_COUNT * 2, msgsC.getMessageCount()); - - assertEquals("Correct forwards from A", MESSAGE_COUNT, brokers.get("BrokerA").broker.getDestination(ActiveMQDestination.transform(dest)).getDestinationStatistics().getForwards().getCount()); - } - - public void initCombosForTestABandBCbrokerNetworkWithSelectors() { - addCombinationValues("dynamicOnly", new Object[]{true, false}); - } - - /** - * BrokerA -> BrokerB -> BrokerC - */ - public void testABandBCbrokerNetworkWithSelectors() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB", dynamicOnly, 2, true); - bridgeBrokers("BrokerB", "BrokerC", dynamicOnly, 2, true); - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", true); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerC", dest, "dummy = 33"); - MessageConsumer clientB = createConsumer("BrokerC", dest, "dummy > 30"); - MessageConsumer clientC = createConsumer("BrokerC", dest, "dummy = 34"); - - // let consumers propagate around the network - Thread.sleep(2000); - // Send messages - // Send messages for broker A - HashMap props = new HashMap<>(); - props.put("dummy", 33); - sendMessages("BrokerA", dest, MESSAGE_COUNT, props); - props.put("dummy", 34); - sendMessages("BrokerA", dest, MESSAGE_COUNT * 2, props); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerC", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerC", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - msgsA.waitForMessagesToArrive(MESSAGE_COUNT); - msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 3); - msgsC.waitForMessagesToArrive(MESSAGE_COUNT * 2); - - assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); - assertEquals(MESSAGE_COUNT * 3, msgsB.getMessageCount()); - assertEquals(MESSAGE_COUNT * 2, msgsC.getMessageCount()); - } - - /** - * BrokerA <- BrokerB -> BrokerC - */ - public void testBAandBCbrokerNetwork() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerB", "BrokerA"); - bridgeBrokers("BrokerB", "BrokerC"); - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", true); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientB = createConsumer("BrokerB", dest); - MessageConsumer clientC = createConsumer("BrokerC", dest); - - //let consumers propagate around the network - Thread.sleep(2000); - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - sendMessages("BrokerB", dest, MESSAGE_COUNT); - sendMessages("BrokerC", dest, MESSAGE_COUNT); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - msgsA.waitForMessagesToArrive(MESSAGE_COUNT * 2); - msgsB.waitForMessagesToArrive(MESSAGE_COUNT); - msgsC.waitForMessagesToArrive(MESSAGE_COUNT * 2); - - assertEquals(MESSAGE_COUNT * 2, msgsA.getMessageCount()); - assertEquals(MESSAGE_COUNT, msgsB.getMessageCount()); - assertEquals(MESSAGE_COUNT * 2, msgsC.getMessageCount()); - } - - /** - * BrokerA -> BrokerB <- BrokerC - */ - public void testABandCBbrokerNetwork() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB"); - bridgeBrokers("BrokerC", "BrokerB"); - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", true); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientB = createConsumer("BrokerB", dest); - MessageConsumer clientC = createConsumer("BrokerC", dest); - - //let consumers propagate around the network - Thread.sleep(2000); - - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - sendMessages("BrokerB", dest, MESSAGE_COUNT); - sendMessages("BrokerC", dest, MESSAGE_COUNT); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - msgsA.waitForMessagesToArrive(MESSAGE_COUNT); - msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 3); - msgsC.waitForMessagesToArrive(MESSAGE_COUNT); - - assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); - assertEquals(MESSAGE_COUNT * 3, msgsB.getMessageCount()); - assertEquals(MESSAGE_COUNT, msgsC.getMessageCount()); - } - - /** - * BrokerA <-> BrokerB <-> BrokerC - */ - public void testAllConnectedBrokerNetwork() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB"); - bridgeBrokers("BrokerB", "BrokerA"); - bridgeBrokers("BrokerB", "BrokerC"); - bridgeBrokers("BrokerC", "BrokerB"); - bridgeBrokers("BrokerA", "BrokerC"); - bridgeBrokers("BrokerC", "BrokerA"); - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", true); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientB = createConsumer("BrokerB", dest); - MessageConsumer clientC = createConsumer("BrokerC", dest); - //let consumers propagate around the network - Thread.sleep(2000); - - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - sendMessages("BrokerB", dest, MESSAGE_COUNT); - sendMessages("BrokerC", dest, MESSAGE_COUNT); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - msgsA.waitForMessagesToArrive(MESSAGE_COUNT * 3); - msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 3); - msgsC.waitForMessagesToArrive(MESSAGE_COUNT * 3); - - assertEquals(MESSAGE_COUNT * 3, msgsA.getMessageCount()); - assertEquals(MESSAGE_COUNT * 3, msgsB.getMessageCount()); - assertEquals(MESSAGE_COUNT * 3, msgsC.getMessageCount()); - } - - public void testAllConnectedBrokerNetworkSingleProducerTTL() throws Exception { - - // duplicates are expected with ttl of 2 as each broker is connected to the next - // but the dups are suppressed by the store and now also by the topic sub when enableAudit - // default (true) is present in a matching destination policy entry - int networkTTL = 2; - boolean conduitSubs = true; - // Setup ring broker networks - bridgeBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduitSubs); - bridgeBrokers("BrokerB", "BrokerA", dynamicOnly, networkTTL, conduitSubs); - bridgeBrokers("BrokerB", "BrokerC", dynamicOnly, networkTTL, conduitSubs); - bridgeBrokers("BrokerC", "BrokerB", dynamicOnly, networkTTL, conduitSubs); - bridgeBrokers("BrokerA", "BrokerC", dynamicOnly, networkTTL, conduitSubs); - bridgeBrokers("BrokerC", "BrokerA", dynamicOnly, networkTTL, conduitSubs); - - PolicyMap policyMap = new PolicyMap(); - // enable audit is on by default just need to give it matching policy entry - // so it will be applied to the topic subscription - policyMap.setDefaultEntry(new PolicyEntry()); - Collection brokerList = brokers.values(); - for (Iterator i = brokerList.iterator(); i.hasNext(); ) { - BrokerService broker = i.next().broker; - broker.setDestinationPolicy(policyMap); - broker.setDeleteAllMessagesOnStartup(true); - } - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", true); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientB = createConsumer("BrokerB", dest); - MessageConsumer clientC = createConsumer("BrokerC", dest); - //let consumers propagate around the network - Thread.sleep(2000); - - // Send messages - sendMessages("BrokerA", dest, 1); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - msgsA.waitForMessagesToArrive(1); - msgsB.waitForMessagesToArrive(1); - msgsC.waitForMessagesToArrive(1); - - // ensure we don't get any more messages - Thread.sleep(2000); - - assertEquals(1, msgsA.getMessageCount()); - assertEquals(1, msgsB.getMessageCount()); - assertEquals(1, msgsC.getMessageCount()); - } - - public void testAllConnectedBrokerNetworkDurableSubTTL() throws Exception { - int networkTTL = 2; - boolean conduitSubs = true; - // Setup ring broker network - bridgeBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduitSubs); - bridgeBrokers("BrokerB", "BrokerA", dynamicOnly, networkTTL, conduitSubs); - bridgeBrokers("BrokerB", "BrokerC", dynamicOnly, networkTTL, conduitSubs); - bridgeBrokers("BrokerC", "BrokerB", dynamicOnly, networkTTL, conduitSubs); - bridgeBrokers("BrokerA", "BrokerC", dynamicOnly, networkTTL, conduitSubs); - bridgeBrokers("BrokerC", "BrokerA", dynamicOnly, networkTTL, conduitSubs); - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", true); - - // Setup consumers - MessageConsumer clientA = createDurableSubscriber("BrokerA", (Topic) dest, "clientA"); - MessageConsumer clientB = createDurableSubscriber("BrokerB", (Topic) dest, "clientB"); - MessageConsumer clientC = createDurableSubscriber("BrokerC", (Topic) dest, "clientC"); - //let consumers propagate around the network - Thread.sleep(2000); - - // Send messages - sendMessages("BrokerA", dest, 1); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - msgsA.waitForMessagesToArrive(1); - msgsB.waitForMessagesToArrive(1); - msgsC.waitForMessagesToArrive(1); - - // ensure we don't get any more messages - Thread.sleep(2000); - - assertEquals(1, msgsA.getMessageCount()); - assertEquals(1, msgsB.getMessageCount()); - assertEquals(1, msgsC.getMessageCount()); - } - - /** - * BrokerA <-> BrokerB <-> BrokerC - */ - public void testAllConnectedUsingMulticast() throws Exception { - // Setup broker networks - bridgeAllBrokers(); - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", true); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientB = createConsumer("BrokerB", dest); - MessageConsumer clientC = createConsumer("BrokerC", dest); - - //let consumers propagate around the network - Thread.sleep(2000); - - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - sendMessages("BrokerB", dest, MESSAGE_COUNT); - sendMessages("BrokerC", dest, MESSAGE_COUNT); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - msgsA.waitForMessagesToArrive(MESSAGE_COUNT * 3); - msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 3); - msgsC.waitForMessagesToArrive(MESSAGE_COUNT * 3); - - assertEquals(MESSAGE_COUNT * 3, msgsA.getMessageCount()); - assertEquals(MESSAGE_COUNT * 3, msgsB.getMessageCount()); - assertEquals(MESSAGE_COUNT * 3, msgsC.getMessageCount()); - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - String options = new String("?persistent=false&useJmx=false"); - createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA" + options)); - createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB" + options)); - createBroker(new URI("broker:(tcp://localhost:61618)/BrokerC" + options)); - } - - @Override - protected void configureBroker(BrokerService broker) { - broker.setBrokerId(broker.getBrokerName()); - } - - public static Test suite() { - return suite(ThreeBrokerTopicNetworkTest.class); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTopicNetworkUsingTcpTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTopicNetworkUsingTcpTest.java deleted file mode 100644 index 8053031f68..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerTopicNetworkUsingTcpTest.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.activemq.usecases; - -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.network.DemandForwardingBridge; -import org.apache.activemq.network.NetworkBridgeConfiguration; -import org.apache.activemq.transport.TransportFactory; - -/** - * - */ -public class ThreeBrokerTopicNetworkUsingTcpTest extends ThreeBrokerTopicNetworkTest { - - protected List bridges; - - protected void bridgeBrokers(BrokerService localBroker, BrokerService remoteBroker) throws Exception { - List remoteTransports = remoteBroker.getTransportConnectors(); - List localTransports = localBroker.getTransportConnectors(); - - URI remoteURI; - URI localURI; - if (!remoteTransports.isEmpty() && !localTransports.isEmpty()) { - remoteURI = remoteTransports.get(0).getConnectUri(); - localURI = localTransports.get(0).getConnectUri(); - - // Ensure that we are connecting using tcp - if (remoteURI.toString().startsWith("tcp:") && localURI.toString().startsWith("tcp:")) { - NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); - config.setBrokerName(localBroker.getBrokerName()); - DemandForwardingBridge bridge = new DemandForwardingBridge(config, TransportFactory.connect(localURI), TransportFactory.connect(remoteURI)); - bridge.setBrokerService(localBroker); - bridges.add(bridge); - - bridge.start(); - } else { - throw new Exception("Remote broker or local broker is not using tcp connectors"); - } - } else { - throw new Exception("Remote broker or local broker has no registered connectors."); - } - - maxSetupTime = 2000; - } - - @Override - public void setUp() throws Exception { - super.setUp(); - - bridges = new ArrayList<>(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerVirtualTopicNetworkLevelDBTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerVirtualTopicNetworkLevelDBTest.java deleted file mode 100644 index 6a20b1267e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerVirtualTopicNetworkLevelDBTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import java.io.File; -import java.io.IOException; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.leveldb.LevelDBStore; - -public class ThreeBrokerVirtualTopicNetworkLevelDBTest extends ThreeBrokerVirtualTopicNetworkTest { - - @Override - protected void configurePersistenceAdapter(BrokerService broker) throws IOException { - File dataFileDir = new File("target/test-data/leveldb/" + broker.getBrokerName()); - LevelDBStore adapter = new LevelDBStore(); - adapter.setDirectory(dataFileDir); - broker.setPersistenceAdapter(adapter); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerVirtualTopicNetworkTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerVirtualTopicNetworkTest.java deleted file mode 100644 index f08499a3cb..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/ThreeBrokerVirtualTopicNetworkTest.java +++ /dev/null @@ -1,188 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Destination; -import javax.jms.MessageConsumer; -import java.io.File; -import java.io.IOException; -import java.net.URI; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.DestinationInterceptor; -import org.apache.activemq.broker.region.virtual.VirtualDestination; -import org.apache.activemq.broker.region.virtual.VirtualDestinationInterceptor; -import org.apache.activemq.broker.region.virtual.VirtualTopic; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.store.kahadb.KahaDBStore; -import org.apache.activemq.util.MessageIdList; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ThreeBrokerVirtualTopicNetworkTest extends JmsMultipleBrokersTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(ThreeBrokerVirtualTopicNetworkTest.class); - protected static final int MESSAGE_COUNT = 1; - public boolean dynamicOnly = false; - - public void testNetworkVirtualTopic() throws Exception { - int networkTTL = 6; - boolean conduitSubs = true; - // Setup broker networks - bridgeAndConfigureBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduitSubs); - bridgeAndConfigureBrokers("BrokerA", "BrokerC", dynamicOnly, networkTTL, conduitSubs); - bridgeAndConfigureBrokers("BrokerB", "BrokerA", dynamicOnly, networkTTL, conduitSubs); - bridgeAndConfigureBrokers("BrokerB", "BrokerC", dynamicOnly, networkTTL, conduitSubs); - bridgeAndConfigureBrokers("BrokerC", "BrokerA", dynamicOnly, networkTTL, conduitSubs); - bridgeAndConfigureBrokers("BrokerC", "BrokerB", dynamicOnly, networkTTL, conduitSubs); - - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", true); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", createDestination("Consumer.A.TEST.FOO", false)); - MessageConsumer clientB = createConsumer("BrokerB", createDestination("Consumer.B.TEST.FOO", false)); - MessageConsumer clientC = createConsumer("BrokerC", createDestination("Consumer.C.TEST.FOO", false)); - - Thread.sleep(2000); - - // Send messages - sendMessages("BrokerA", dest, 1); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - MessageIdList msgsC = getConsumerMessages("BrokerC", clientC); - - msgsA.waitForMessagesToArrive(1); - msgsB.waitForMessagesToArrive(1); - msgsC.waitForMessagesToArrive(1); - - // ensure we don't get any more messages - Thread.sleep(2000); - - assertEquals(1, msgsA.getMessageCount()); - assertEquals(1, msgsB.getMessageCount()); - assertEquals(1, msgsC.getMessageCount()); - - // restart to ensure no hanging messages - LOG.info("Restarting brokerA"); - BrokerItem brokerItem = brokers.remove("BrokerA"); - if (brokerItem != null) { - brokerItem.destroy(); - } - - BrokerService restartedBroker = createAndConfigureBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?useJmx=false")); - bridgeAndConfigureBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduitSubs); - bridgeAndConfigureBrokers("BrokerA", "BrokerC", dynamicOnly, networkTTL, conduitSubs); - restartedBroker.start(); - waitForBridgeFormation(); - - clientA = createConsumer("BrokerA", createDestination("Consumer.A.TEST.FOO", false)); - LOG.info("recreated clientA"); - - Thread.sleep(2000); - - sendMessages("BrokerA", dest, 10); - - msgsA = getConsumerMessages("BrokerA", clientA); - - msgsA.waitForMessagesToArrive(10); - msgsB.waitForMessagesToArrive(11); - msgsC.waitForMessagesToArrive(11); - - // ensure we don't get any more messages - Thread.sleep(2000); - - LOG.info("MessagesA: " + msgsA.getMessageIds()); - assertEquals(10, msgsA.getMessageCount()); - assertEquals(11, msgsB.getMessageCount()); - assertEquals(11, msgsC.getMessageCount()); - - // restart to ensure no hanging messages - LOG.info("Restarting brokerA again"); - brokerItem = brokers.remove("BrokerA"); - if (brokerItem != null) { - brokerItem.destroy(); - } - - restartedBroker = createAndConfigureBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?useJmx=false")); - bridgeAndConfigureBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduitSubs); - bridgeAndConfigureBrokers("BrokerA", "BrokerC", dynamicOnly, networkTTL, conduitSubs); - restartedBroker.start(); - waitForBridgeFormation(); - - clientA = createConsumer("BrokerA", createDestination("Consumer.A.TEST.FOO", false)); - LOG.info("recreated clientA again"); - - Thread.sleep(2000); - - msgsA = getConsumerMessages("BrokerA", clientA); - - // ensure we don't get any more messages - Thread.sleep(5000); - - LOG.info("Extra MessagesA: " + msgsA.getMessageIds()); - assertEquals(0, msgsA.getMessageCount()); - assertEquals(11, msgsB.getMessageCount()); - assertEquals(11, msgsC.getMessageCount()); - } - - private void bridgeAndConfigureBrokers(String local, - String remote, - boolean dynamicOnly, - int networkTTL, - boolean conduitSubs) throws Exception { - NetworkConnector bridge = bridgeBrokers(local, remote, dynamicOnly, networkTTL, conduitSubs); - bridge.setDecreaseNetworkConsumerPriority(true); - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - String options = new String("?useJmx=false&deleteAllMessagesOnStartup=true"); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61616)/BrokerA" + options)); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61617)/BrokerB" + options)); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61618)/BrokerC" + options)); - } - - private BrokerService createAndConfigureBroker(URI uri) throws Exception { - BrokerService broker = createBroker(uri); - - configurePersistenceAdapter(broker); - - // make all topics virtual and consumers use the default prefix - VirtualDestinationInterceptor virtualDestinationInterceptor = new VirtualDestinationInterceptor(); - virtualDestinationInterceptor.setVirtualDestinations(new VirtualDestination[]{new VirtualTopic()}); - DestinationInterceptor[] destinationInterceptors = new DestinationInterceptor[]{virtualDestinationInterceptor}; - broker.setDestinationInterceptors(destinationInterceptors); - return broker; - } - - protected void configurePersistenceAdapter(BrokerService broker) throws IOException { - File dataFileDir = new File("target/test-amq-data/kahadb/" + broker.getBrokerName()); - KahaDBStore kaha = new KahaDBStore(); - kaha.setDirectory(dataFileDir); - broker.setPersistenceAdapter(kaha); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicDurableConnectStatsTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicDurableConnectStatsTest.java deleted file mode 100644 index 02d175c077..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicDurableConnectStatsTest.java +++ /dev/null @@ -1,268 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.management.MBeanServerConnection; -import javax.management.MBeanServerInvocationHandler; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; -import java.io.IOException; -import java.lang.management.ManagementFactory; -import java.util.Date; -import java.util.Vector; - -import junit.framework.Test; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ActiveMQPrefetchPolicy; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.jmx.DurableSubscriptionViewMBean; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.util.Wait; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class TopicDurableConnectStatsTest extends org.apache.activemq.TestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(TopicDurableConnectStatsTest.class); - private BrokerService broker; - private ActiveMQTopic topic; - private final Vector exceptions = new Vector<>(); - private final int messageSize = 4000; - protected MBeanServerConnection mbeanServer; - protected String domain = "org.apache.activemq"; - private ActiveMQConnectionFactory connectionFactory = null; - final int numMessages = 20; - - private static Session session2 = null; - - @Override - protected ActiveMQConnectionFactory createConnectionFactory() throws Exception { - - connectionFactory = new ActiveMQConnectionFactory("vm://" + getName(true)); - - ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); - prefetchPolicy.setAll(10); - connectionFactory.setPrefetchPolicy(prefetchPolicy); - - connectionFactory.setWatchTopicAdvisories(false); - return connectionFactory; - } - - @Override - protected Connection createConnection() throws Exception { - return createConnection("cliName"); - } - - protected Connection createConnection(String name) throws Exception { - Connection con = super.createConnection(); - con.setClientID(name); - con.start(); - return con; - } - - public static Test suite() { - return suite(TopicDurableConnectStatsTest.class); - } - - @Override - protected void setUp() throws Exception { - exceptions.clear(); - topic = (ActiveMQTopic) createDestination(); - - createBroker(); - mbeanServer = ManagementFactory.getPlatformMBeanServer(); - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - destroyBroker(); - } - - private void createBroker() throws Exception { - createBroker(true); - } - - private void createBroker(boolean deleteAllMessages) throws Exception { - broker = BrokerFactory.createBroker("broker:(vm://" + getName(true) + ")"); - broker.setBrokerName(getName(true)); - broker.setDeleteAllMessagesOnStartup(deleteAllMessages); - broker.setAdvisorySupport(false); - broker.addConnector("tcp://0.0.0.0:0"); - - setDefaultPersistenceAdapter(broker); - broker.start(); - } - - private void destroyBroker() throws Exception { - if (broker != null) - broker.stop(); - } - - protected ObjectName assertRegisteredObjectName(String name) throws MalformedObjectNameException, NullPointerException { - ObjectName objectName = new ObjectName(name); - - LOG.info("** Looking for " + name); - try { - if (mbeanServer.isRegistered(objectName)) { - LOG.info("Bean Registered: " + objectName); - } else { - LOG.info("Couldn't find Mbean! " + objectName); - - } - } catch (IOException e) { - e.printStackTrace(); - } - return objectName; - } - - public void testPendingTopicStat() throws Exception { - - Connection consumerCon = createConnection("cliId1"); - Session consumerSession = consumerCon.createSession(true, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer1 = consumerSession.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - assertNotNull(consumer1); - - DurableSubscriptionViewMBean subscriber1 = null; - - ObjectName query = new ObjectName(domain + ":type=Broker,brokerName=" + getName(true) + ",destinationType=Topic,destinationName=" + topic.getTopicName() + ",endpoint=Consumer,clientId=cliId1,consumerId=*"); - - java.util.Set set = mbeanServer.queryNames(query, null); - - ObjectName subscriberObjName1 = set.iterator().next(); - subscriber1 = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, subscriberObjName1, DurableSubscriptionViewMBean.class, true); - - LOG.info("Beginning Pending Queue Size count: " + subscriber1.getPendingQueueSize()); - LOG.info("Prefetch Limit: " + subscriber1.getPrefetchSize()); - - assertEquals("no pending", 0, subscriber1.getPendingQueueSize()); - assertEquals("Prefetch Limit ", 10, subscriber1.getPrefetchSize()); - - Connection producerCon = createConnection("x"); - Session producerSessions = producerCon.createSession(true, Session.AUTO_ACKNOWLEDGE); - - MessageProducer producer = producerSessions.createProducer(topic); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - - int i = 0; - for (; i < numMessages; i++) { - - if (i == 15) { - // kill consumer - - LOG.info("Killing consumer at 15"); - consumerSession.close(); - consumerCon.close(); - } - - TextMessage message = producerSessions.createTextMessage(createMessageText(i)); - message.setJMSExpiration(0); - message.setStringProperty("filter", "true"); - producer.send(topic, message); - producerSessions.commit(); - - } - LOG.info("Sent " + i + " messages in total"); - producerCon.close(); - - LOG.info("Pending Queue Size count: " + subscriber1.getPendingQueueSize()); - assertEquals("pending as expected", 20, subscriber1.getPendingQueueSize()); - - LOG.info("Re-connect client and consume messages"); - Connection con2 = createConnection("cliId1"); - session2 = con2.createSession(true, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer2 = session2.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); - - final Listener listener = new Listener(); - consumer2.setMessageListener(listener); - - assertTrue("received all sent", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return numMessages == listener.count; - } - })); - - LOG.info("Received: " + listener.count); - - int pq = subscriber1.getPendingQueueSize(); - LOG.info("Pending Queue Size count: " + pq); - assertEquals("Pending queue after consumed", 0, pq); - - session2.close(); - con2.close(); - LOG.info("FINAL Pending Queue Size count (after consumer close): " + subscriber1.getPendingQueueSize()); - } - - private String createMessageText(int index) { - StringBuffer buffer = new StringBuffer(messageSize); - buffer.append("Message: " + index + " sent at: " + new Date()); - if (buffer.length() > messageSize) { - return buffer.substring(0, messageSize); - } - for (int i = buffer.length(); i < messageSize; i++) { - buffer.append(' '); - } - return buffer.toString(); - } - - public static class Listener implements MessageListener { - - int count = 0; - String id = null; - - Listener() { - } - - @Override - public void onMessage(Message message) { - count++; - try { - session2.commit(); - } catch (JMSException e1) { - e1.printStackTrace(); - } - - if (id != null) { - try { - LOG.info(id + ", " + message.getJMSMessageID()); - } catch (Exception ignored) { - } - } - - try { - Thread.sleep(2); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } -} - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicProducerFlowControlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicProducerFlowControlTest.java deleted file mode 100644 index 663afb4547..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicProducerFlowControlTest.java +++ /dev/null @@ -1,194 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.Message; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import java.util.Arrays; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ActiveMQPrefetchPolicy; -import org.apache.activemq.advisory.AdvisorySupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.util.Wait; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class TopicProducerFlowControlTest extends TestCase implements MessageListener { - - private static final Logger LOG = LoggerFactory.getLogger(TopicProducerFlowControlTest.class); - private static final String brokerName = "testBroker"; - private static final String brokerUrl = "vm://" + brokerName; - protected static final int destinationMemLimit = 2097152; // 2MB - private static final AtomicLong produced = new AtomicLong(); - private static final AtomicLong consumed = new AtomicLong(); - private static final int numMessagesToSend = 50000; - - private BrokerService broker; - - @Override - protected void setUp() throws Exception { - // Setup and start the broker - broker = new BrokerService(); - broker.setBrokerName(brokerName); - broker.setPersistent(false); - broker.setSchedulerSupport(false); - broker.setUseJmx(false); - broker.setUseShutdownHook(false); - broker.addConnector(brokerUrl); - - // Setup the destination policy - PolicyMap pm = new PolicyMap(); - - // Setup the topic destination policy - PolicyEntry tpe = new PolicyEntry(); - tpe.setTopic(">"); - tpe.setMemoryLimit(destinationMemLimit); - tpe.setProducerFlowControl(true); - tpe.setAdvisoryWhenFull(true); - - // Setup the topic destination policy - PolicyEntry qpe = new PolicyEntry(); - qpe.setQueue(">"); - qpe.setMemoryLimit(destinationMemLimit); - qpe.setProducerFlowControl(true); - qpe.setQueuePrefetch(1); - qpe.setAdvisoryWhenFull(true); - - pm.setPolicyEntries(Arrays.asList(new PolicyEntry[]{tpe, qpe})); - - setDestinationPolicy(broker, pm); - - // Start the broker - broker.start(); - broker.waitUntilStarted(); - } - - protected void setDestinationPolicy(BrokerService broker, PolicyMap pm) { - broker.setDestinationPolicy(pm); - } - - @Override - protected void tearDown() throws Exception { - broker.stop(); - broker.waitUntilStopped(); - } - - public void testTopicProducerFlowControl() throws Exception { - - // Create the connection factory - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl); - connectionFactory.setAlwaysSyncSend(true); - connectionFactory.setProducerWindowSize(1024); - - ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); - prefetchPolicy.setAll(5000); - connectionFactory.setPrefetchPolicy(prefetchPolicy); - // Start the test destination listener - Connection c = connectionFactory.createConnection(); - c.start(); - Session listenerSession = c.createSession(false, 1); - Destination destination = createDestination(listenerSession); - - listenerSession.createConsumer(destination).setMessageListener(new TopicProducerFlowControlTest()); - final AtomicInteger blockedCounter = new AtomicInteger(0); - listenerSession.createConsumer(new ActiveMQTopic(AdvisorySupport.FULL_TOPIC_PREFIX + ">")).setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - LOG.info("Got full advisory, blockedCounter: " + blockedCounter.get()); - blockedCounter.incrementAndGet(); - } - }); - - // Start producing the test messages - final Session session = connectionFactory.createConnection().createSession(false, Session.AUTO_ACKNOWLEDGE); - final MessageProducer producer = session.createProducer(destination); - - Thread producingThread = new Thread("Producing Thread") { - @Override - public void run() { - try { - for (long i = 0; i < numMessagesToSend; i++) { - producer.send(session.createTextMessage("test")); - - long count = produced.incrementAndGet(); - if (count % 10000 == 0) { - LOG.info("Produced " + count + " messages"); - } - } - } catch (Throwable ex) { - ex.printStackTrace(); - } finally { - try { - producer.close(); - session.close(); - } catch (Exception e) { - } - } - } - }; - - producingThread.start(); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return consumed.get() == numMessagesToSend; - } - }, 5 * 60 * 1000); // give it plenty of time before failing - - assertEquals("Didn't produce all messages", numMessagesToSend, produced.get()); - assertEquals("Didn't consume all messages", numMessagesToSend, consumed.get()); - - assertTrue("Producer got blocked", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return blockedCounter.get() > 0; - } - }, 5 * 1000)); - } - - protected Destination createDestination(Session listenerSession) throws Exception { - return new ActiveMQTopic("test"); - } - - @Override - public void onMessage(Message message) { - long count = consumed.incrementAndGet(); - if (count % 100 == 0) { - try { - Thread.sleep(100); - } catch (InterruptedException e) { - } - } - if (count % 10000 == 0) { - LOG.info("\tConsumed " + count + " messages"); - } - - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicRedeliverTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicRedeliverTest.java deleted file mode 100644 index 937a3c45e0..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicRedeliverTest.java +++ /dev/null @@ -1,285 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.ExceptionListener; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.jms.Topic; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.activemq.test.TestSupport; -import org.apache.activemq.util.IdGenerator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class TopicRedeliverTest extends TestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(TopicRedeliverTest.class); - private static final int RECEIVE_TIMEOUT = 10000; - - protected int deliveryMode = DeliveryMode.PERSISTENT; - private IdGenerator idGen = new IdGenerator(); - - public TopicRedeliverTest() { - } - - public TopicRedeliverTest(String n) { - super(n); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - topic = true; - } - - /** - * test messages are acknowledged and recovered properly - * - * @throws Exception - */ - public void testClientAcknowledge() throws Exception { - Destination destination = createDestination(getClass().getName()); - Connection connection = createConnection(); - connection.setClientID(idGen.generateId()); - connection.start(); - Session consumerSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = consumerSession.createConsumer(destination); - Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = producerSession.createProducer(destination); - producer.setDeliveryMode(deliveryMode); - - // send some messages - - TextMessage sent1 = producerSession.createTextMessage(); - sent1.setText("msg1"); - sent1.setStringProperty("str", "1"); - producer.send(sent1); - - TextMessage sent2 = producerSession.createTextMessage(); - sent2.setText("msg2"); - sent2.setStringProperty("str", "2"); - producer.send(sent2); - - TextMessage sent3 = producerSession.createTextMessage(); - sent2.setText("msg3"); - sent2.setStringProperty("str", "3"); - producer.send(sent3); - - TextMessage msgTest = (TextMessage) consumer.receive(RECEIVE_TIMEOUT); - System.out.println("msgTest::" + msgTest + " // " + msgTest.getText()); - TextMessage rec2 = (TextMessage) consumer.receive(RECEIVE_TIMEOUT); - System.out.println("msgTest::" + rec2 + " // " + rec2.getText()); - assertNull(consumer.receiveNoWait()); - - // ack rec2 - rec2.acknowledge(); - - TextMessage sent4 = producerSession.createTextMessage(); - sent4.setText("msg4"); - producer.send(sent4); - - TextMessage rec4 = (TextMessage) consumer.receive(RECEIVE_TIMEOUT); - assertTrue(rec4.equals(sent4)); - consumerSession.recover(); - rec4 = (TextMessage) consumer.receive(RECEIVE_TIMEOUT); - assertTrue(rec4.equals(sent4)); - assertTrue(rec4.getJMSRedelivered()); - rec4.acknowledge(); - connection.close(); - - } - - /** - * Test redelivered flag is set on rollbacked transactions - * - * @throws Exception - */ - public void testRedilveredFlagSetOnRollback() throws Exception { - Destination destination = createDestination(getClass().getName()); - Connection connection = createConnection(); - connection.setClientID(idGen.generateId()); - connection.start(); - Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = null; - if (topic) { - consumer = consumerSession.createDurableSubscriber((Topic) destination, "TESTRED"); - } else { - consumer = consumerSession.createConsumer(destination); - } - Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = producerSession.createProducer(destination); - producer.setDeliveryMode(deliveryMode); - - TextMessage sentMsg = producerSession.createTextMessage(); - sentMsg.setText("msg1"); - producer.send(sentMsg); - producerSession.commit(); - - Message recMsg = consumer.receive(RECEIVE_TIMEOUT); - assertFalse(recMsg.getJMSRedelivered()); - recMsg = consumer.receive(RECEIVE_TIMEOUT); - consumerSession.rollback(); - recMsg = consumer.receive(RECEIVE_TIMEOUT); - assertTrue(recMsg.getJMSRedelivered()); - consumerSession.commit(); - assertTrue(recMsg.equals(sentMsg)); - assertTrue(recMsg.getJMSRedelivered()); - connection.close(); - } - - public void testNoExceptionOnRedeliveryAckWithSimpleTopicConsumer() throws Exception { - Destination destination = createDestination(getClass().getName()); - Connection connection = createConnection(); - final AtomicBoolean gotException = new AtomicBoolean(); - connection.setExceptionListener(new ExceptionListener() { - @Override - public void onException(JMSException exception) { - LOG.error("unexpected ex:" + exception); - gotException.set(true); - } - }); - connection.setClientID(idGen.generateId()); - connection.start(); - Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = null; - if (topic) { - consumer = consumerSession.createConsumer(destination); - } else { - consumer = consumerSession.createConsumer(destination); - } - Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = producerSession.createProducer(destination); - producer.setDeliveryMode(deliveryMode); - - TextMessage sentMsg = producerSession.createTextMessage(); - sentMsg.setText("msg1"); - producer.send(sentMsg); - producerSession.commit(); - - Message recMsg = consumer.receive(RECEIVE_TIMEOUT); - assertFalse(recMsg.getJMSRedelivered()); - recMsg = consumer.receive(RECEIVE_TIMEOUT); - consumerSession.rollback(); - recMsg = consumer.receive(RECEIVE_TIMEOUT); - assertTrue(recMsg.getJMSRedelivered()); - consumerSession.rollback(); - recMsg = consumer.receive(RECEIVE_TIMEOUT); - assertTrue(recMsg.getJMSRedelivered()); - consumerSession.commit(); - assertTrue(recMsg.equals(sentMsg)); - assertTrue(recMsg.getJMSRedelivered()); - connection.close(); - - assertFalse("no exception", gotException.get()); - } - - /** - * Check a session is rollbacked on a Session close(); - * - * @throws Exception - */ - - public void xtestTransactionRollbackOnSessionClose() throws Exception { - Destination destination = createDestination(getClass().getName()); - Connection connection = createConnection(); - connection.setClientID(idGen.generateId()); - connection.start(); - Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = null; - if (topic) { - consumer = consumerSession.createDurableSubscriber((Topic) destination, "TESTRED"); - } else { - consumer = consumerSession.createConsumer(destination); - } - Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = producerSession.createProducer(destination); - producer.setDeliveryMode(deliveryMode); - - TextMessage sentMsg = producerSession.createTextMessage(); - sentMsg.setText("msg1"); - producer.send(sentMsg); - - producerSession.commit(); - - Message recMsg = consumer.receive(RECEIVE_TIMEOUT); - assertFalse(recMsg.getJMSRedelivered()); - consumerSession.close(); - consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - consumer = consumerSession.createConsumer(destination); - - recMsg = consumer.receive(RECEIVE_TIMEOUT); - consumerSession.commit(); - assertTrue(recMsg.equals(sentMsg)); - connection.close(); - } - - /** - * check messages are actuallly sent on a tx rollback - * - * @throws Exception - */ - - public void testTransactionRollbackOnSend() throws Exception { - Destination destination = createDestination(getClass().getName()); - Connection connection = createConnection(); - connection.setClientID(idGen.generateId()); - connection.start(); - Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = consumerSession.createConsumer(destination); - Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = producerSession.createProducer(destination); - producer.setDeliveryMode(deliveryMode); - - TextMessage sentMsg = producerSession.createTextMessage(); - sentMsg.setText("msg1"); - producer.send(sentMsg); - producerSession.commit(); - - Message recMsg = consumer.receive(RECEIVE_TIMEOUT); - consumerSession.commit(); - assertTrue(recMsg.equals(sentMsg)); - - sentMsg = producerSession.createTextMessage(); - sentMsg.setText("msg2"); - producer.send(sentMsg); - producerSession.rollback(); - - sentMsg = producerSession.createTextMessage(); - sentMsg.setText("msg3"); - producer.send(sentMsg); - producerSession.commit(); - - recMsg = consumer.receive(RECEIVE_TIMEOUT); - assertTrue(recMsg.equals(sentMsg)); - consumerSession.commit(); - - connection.close(); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicReplicationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicReplicationTest.java deleted file mode 100644 index 0f252dda24..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicReplicationTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Destination; -import javax.jms.MessageConsumer; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.util.MessageIdList; -import org.springframework.core.io.ClassPathResource; - -public class TopicReplicationTest extends JmsMultipleBrokersTestSupport { - - public static final int MSG_COUNT = 10; - - public void testReplication() throws Exception { - createBroker(new ClassPathResource("org/apache/activemq/usecases/replication-broker1.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/replication-broker2.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/replication-broker3.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/replication-broker4.xml")); - - brokers.get("replication-broker1").broker.waitUntilStarted(); - brokers.get("replication-broker2").broker.waitUntilStarted(); - brokers.get("replication-broker3").broker.waitUntilStarted(); - brokers.get("replication-broker4").broker.waitUntilStarted(); - - Destination dest = createDestination("replication", true); - - // Setup consumers - MessageConsumer clientA = createConsumer("replication-broker2", dest); - MessageConsumer clientB = createConsumer("replication-broker3", dest); - MessageConsumer clientC = createConsumer("replication-broker4", dest); - MessageConsumer clientD = createConsumer("replication-broker4", dest); - - //let consumers propagate around the network - Thread.sleep(2000); - - // Get message count - MessageIdList msgsA = getConsumerMessages("replication-broker2", clientA); - MessageIdList msgsB = getConsumerMessages("replication-broker3", clientB); - MessageIdList msgsC = getConsumerMessages("replication-broker4", clientC); - MessageIdList msgsD = getConsumerMessages("replication-broker4", clientD); - - // send messages to broker1 - sendMessages("replication-broker1", dest, MSG_COUNT); - - msgsA.waitForMessagesToArrive(MSG_COUNT); - msgsB.waitForMessagesToArrive(MSG_COUNT); - msgsC.waitForMessagesToArrive(MSG_COUNT); - msgsD.waitForMessagesToArrive(MSG_COUNT); - - assertEquals(MSG_COUNT, msgsA.getMessageCount()); - assertEquals(MSG_COUNT, msgsB.getMessageCount()); - assertEquals(MSG_COUNT, msgsC.getMessageCount()); - assertEquals(MSG_COUNT, msgsD.getMessageCount()); - - // send messages to broker4 - sendMessages("replication-broker4", dest, MSG_COUNT); - - msgsA.waitForMessagesToArrive(2 * MSG_COUNT); - msgsB.waitForMessagesToArrive(2 * MSG_COUNT); - msgsC.waitForMessagesToArrive(2 * MSG_COUNT); - msgsD.waitForMessagesToArrive(2 * MSG_COUNT); - - assertEquals(2 * MSG_COUNT, msgsA.getMessageCount()); - assertEquals(2 * MSG_COUNT, msgsB.getMessageCount()); - assertEquals(2 * MSG_COUNT, msgsC.getMessageCount()); - assertEquals(2 * MSG_COUNT, msgsD.getMessageCount()); - - // send messages to broker3 - sendMessages("replication-broker3", dest, MSG_COUNT); - - msgsA.waitForMessagesToArrive(3 * MSG_COUNT); - msgsB.waitForMessagesToArrive(3 * MSG_COUNT); - msgsC.waitForMessagesToArrive(3 * MSG_COUNT); - msgsD.waitForMessagesToArrive(3 * MSG_COUNT); - - assertEquals(3 * MSG_COUNT, msgsA.getMessageCount()); - assertEquals(3 * MSG_COUNT, msgsB.getMessageCount()); - assertEquals(3 * MSG_COUNT, msgsC.getMessageCount()); - assertEquals(3 * MSG_COUNT, msgsD.getMessageCount()); - - // send messages to broker2 - sendMessages("replication-broker2", dest, MSG_COUNT); - - msgsA.waitForMessagesToArrive(4 * MSG_COUNT); - msgsB.waitForMessagesToArrive(4 * MSG_COUNT); - msgsC.waitForMessagesToArrive(4 * MSG_COUNT); - msgsD.waitForMessagesToArrive(4 * MSG_COUNT); - - assertEquals(4 * MSG_COUNT, msgsA.getMessageCount()); - assertEquals(4 * MSG_COUNT, msgsB.getMessageCount()); - assertEquals(4 * MSG_COUNT, msgsC.getMessageCount()); - assertEquals(4 * MSG_COUNT, msgsD.getMessageCount()); - - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicSubscriptionSlowConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicSubscriptionSlowConsumerTest.java deleted file mode 100644 index 803c198688..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicSubscriptionSlowConsumerTest.java +++ /dev/null @@ -1,123 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.advisory.AdvisorySupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQTopic; -import org.junit.Assert; - -/** - * Checks to see if "slow consumer advisory messages" are generated when - * small number of messages (2) are published to a topic which has a subscriber - * with a prefetch of one set. - */ - -public class TopicSubscriptionSlowConsumerTest extends TestCase { - - private static final String TOPIC_NAME = "slow.consumer"; - Connection connection; - private Session session; - private ActiveMQTopic destination; - private MessageProducer producer; - private MessageConsumer consumer; - private BrokerService brokerService; - - @Override - public void setUp() throws Exception { - - brokerService = createBroker(); - - ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory("vm://localhost"); - - activeMQConnectionFactory.setWatchTopicAdvisories(true); - connection = activeMQConnectionFactory.createConnection(); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = new ActiveMQTopic(TOPIC_NAME); - producer = session.createProducer(destination); - - connection.start(); - } - - public void testPrefetchValueOne() throws Exception { - - ActiveMQTopic consumerDestination = new ActiveMQTopic(TOPIC_NAME + "?consumer.prefetchSize=1"); - consumer = session.createConsumer(consumerDestination); - - //add a consumer to the slow consumer advisory topic. - ActiveMQTopic slowConsumerAdvisoryTopic = AdvisorySupport.getSlowConsumerAdvisoryTopic(destination); - MessageConsumer slowConsumerAdvisory = session.createConsumer(slowConsumerAdvisoryTopic); - - //publish 2 messages - Message txtMessage = session.createTextMessage("Sample Text Message"); - for (int i = 0; i < 2; i++) { - producer.send(txtMessage); - } - - //consume 2 messages - for (int i = 0; i < 2; i++) { - Message receivedMsg = consumer.receive(100); - Assert.assertNotNull("received msg " + i + " should not be null", receivedMsg); - } - - //check for "slow consumer" advisory message - Message slowAdvisoryMessage = slowConsumerAdvisory.receive(100); - Assert.assertNull("should not have received a slow consumer advisory message", slowAdvisoryMessage); - - } - - @Override - public void tearDown() throws Exception { - consumer.close(); - producer.close(); - session.close(); - connection.close(); - brokerService.stop(); - } - - //helper method to create a broker with slow consumer advisory turned on - private BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("localhost"); - broker.setUseJmx(true); - broker.setDeleteAllMessagesOnStartup(true); - broker.addConnector("vm://localhost"); - - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setAdvisoryForSlowConsumers(true); - - policyMap.setDefaultEntry(defaultEntry); - - broker.setDestinationPolicy(policyMap); - broker.start(); - broker.waitUntilStarted(); - return broker; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicSubscriptionZeroPrefetchTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicSubscriptionZeroPrefetchTest.java deleted file mode 100644 index 04674b891e..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TopicSubscriptionZeroPrefetchTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQTopic; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -public class TopicSubscriptionZeroPrefetchTest { - - private static final String TOPIC_NAME = "slow.consumer"; - private Connection connection; - private Session session; - private ActiveMQTopic destination; - private MessageProducer producer; - private MessageConsumer consumer; - private BrokerService brokerService; - - @Before - public void setUp() throws Exception { - - brokerService = createBroker(); - - ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory("vm://localhost"); - - activeMQConnectionFactory.setWatchTopicAdvisories(true); - connection = activeMQConnectionFactory.createConnection(); - connection.setClientID("ClientID-1"); - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - destination = new ActiveMQTopic(TOPIC_NAME); - producer = session.createProducer(destination); - - connection.start(); - } - - /* - * test non durable topic subscription with prefetch set to zero - */ - @Test(timeout = 60000) - public void testTopicConsumerPrefetchZero() throws Exception { - - ActiveMQTopic consumerDestination = new ActiveMQTopic(TOPIC_NAME + "?consumer.retroactive=true&consumer.prefetchSize=0"); - consumer = session.createConsumer(consumerDestination); - - // publish messages - Message txtMessage = session.createTextMessage("M"); - producer.send(txtMessage); - - Message consumedMessage = consumer.receiveNoWait(); - - Assert.assertNotNull("should have received a message the published message", consumedMessage); - } - - /* - * test durable topic subscription with prefetch zero - */ - @Test(timeout = 60000) - public void testDurableTopicConsumerPrefetchZero() throws Exception { - - ActiveMQTopic consumerDestination = new ActiveMQTopic(TOPIC_NAME + "?consumer.prefetchSize=0"); - consumer = session.createDurableSubscriber(consumerDestination, "mysub1"); - - // publish messages - Message txtMessage = session.createTextMessage("M"); - producer.send(txtMessage); - - Message consumedMessage = consumer.receive(100); - - Assert.assertNotNull("should have received a message the published message", consumedMessage); - } - - @After - public void tearDown() throws Exception { - consumer.close(); - producer.close(); - session.close(); - connection.close(); - brokerService.stop(); - } - - // helper method to create a broker with slow consumer advisory turned on - private BrokerService createBroker() throws Exception { - BrokerService broker = new BrokerService(); - broker.setBrokerName("localhost"); - broker.setUseJmx(false); - broker.setDeleteAllMessagesOnStartup(true); - broker.addConnector("vm://localhost"); - broker.start(); - broker.waitUntilStarted(); - return broker; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransactionRollbackOrderTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransactionRollbackOrderTest.java deleted file mode 100644 index 8d1752e6cc..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransactionRollbackOrderTest.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.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.command.ActiveMQQueue; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Test case for AMQ-268 - * - * @author Paul Smith - */ -public final class TransactionRollbackOrderTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(TransactionRollbackOrderTest.class); - - private volatile String receivedText; - - private Session producerSession; - private Session consumerSession; - private Destination queue; - - private MessageProducer producer; - private MessageConsumer consumer; - private Connection connection; - private CountDownLatch latch = new CountDownLatch(1); - private int numMessages = 5; - private List msgSent = new ArrayList<>(); - private List msgCommitted = new ArrayList<>(); - private List msgRolledBack = new ArrayList<>(); - private List msgRedelivered = new ArrayList<>(); - - public void testTransaction() throws Exception { - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); - - connection = factory.createConnection(); - queue = new ActiveMQQueue(getClass().getName() + "." + getName()); - - producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumerSession = connection.createSession(true, 0); - - producer = producerSession.createProducer(queue); - - consumer = consumerSession.createConsumer(queue); - consumer.setMessageListener(new MessageListener() { - - int msgCount; - int msgCommittedCount; - - @Override - public void onMessage(Message m) { - try { - msgCount++; - TextMessage tm = (TextMessage) m; - receivedText = tm.getText(); - - if (tm.getJMSRedelivered()) { - msgRedelivered.add(receivedText); - } - - LOG.info("consumer received message: " + receivedText + (tm.getJMSRedelivered() ? " ** Redelivered **" : "")); - if (msgCount == 3) { - msgRolledBack.add(receivedText); - consumerSession.rollback(); - LOG.info("[msg: " + receivedText + "] ** rolled back **"); - } else { - msgCommittedCount++; - msgCommitted.add(receivedText); - consumerSession.commit(); - LOG.info("[msg: " + receivedText + "] committed transaction "); - } - if (msgCommittedCount == numMessages) { - latch.countDown(); - } - } catch (JMSException e) { - try { - consumerSession.rollback(); - LOG.info("rolled back transaction"); - } catch (JMSException e1) { - LOG.info(e1.toString()); - e1.printStackTrace(); - } - LOG.info(e.toString()); - e.printStackTrace(); - } - } - }); - connection.start(); - - TextMessage tm = null; - try { - for (int i = 1; i <= numMessages; i++) { - tm = producerSession.createTextMessage(); - tm.setText("Hello " + i); - msgSent.add(tm.getText()); - producer.send(tm); - LOG.info("producer sent message: " + tm.getText()); - } - } catch (JMSException e) { - e.printStackTrace(); - } - - LOG.info("Waiting for latch"); - latch.await(); - - assertEquals(1, msgRolledBack.size()); - assertEquals(1, msgRedelivered.size()); - - LOG.info("msg RolledBack = " + msgRolledBack.get(0)); - LOG.info("msg Redelivered = " + msgRedelivered.get(0)); - - assertEquals(msgRolledBack.get(0), msgRedelivered.get(0)); - - assertEquals(numMessages, msgSent.size()); - assertEquals(numMessages, msgCommitted.size()); - - assertEquals(msgSent, msgCommitted); - - } - - @Override - protected void tearDown() throws Exception { - if (connection != null) { - LOG.info("Closing the connection"); - connection.close(); - } - super.tearDown(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransactionTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransactionTest.java deleted file mode 100644 index fb6c641332..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransactionTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.util.Date; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.command.ActiveMQQueue; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author pragmasoft - */ -public final class TransactionTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(TransactionTest.class); - - private volatile String receivedText; - - private Session producerSession; - private Session consumerSession; - private Destination queue; - - private MessageProducer producer; - private MessageConsumer consumer; - private Connection connection; - private final CountDownLatch latch = new CountDownLatch(1); - - public void testTransaction() throws Exception { - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); - connection = factory.createConnection(); - queue = new ActiveMQQueue(getClass().getName() + "." + getName()); - - producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumerSession = connection.createSession(true, 0); - - producer = producerSession.createProducer(queue); - - consumer = consumerSession.createConsumer(queue); - consumer.setMessageListener(new MessageListener() { - - @Override - public void onMessage(Message m) { - try { - TextMessage tm = (TextMessage) m; - receivedText = tm.getText(); - latch.countDown(); - - LOG.info("consumer received message :" + receivedText); - consumerSession.commit(); - LOG.info("committed transaction"); - } catch (JMSException e) { - try { - consumerSession.rollback(); - LOG.info("rolled back transaction"); - } catch (JMSException e1) { - LOG.info(e1.toString()); - e1.printStackTrace(); - } - LOG.info(e.toString()); - e.printStackTrace(); - } - } - }); - - connection.start(); - - TextMessage tm = null; - try { - tm = producerSession.createTextMessage(); - tm.setText("Hello, " + new Date()); - producer.send(tm); - LOG.info("producer sent message :" + tm.getText()); - } catch (JMSException e) { - e.printStackTrace(); - } - - LOG.info("Waiting for latch"); - latch.await(2, TimeUnit.SECONDS); - assertNotNull(receivedText); - LOG.info("test completed, destination=" + receivedText); - } - - @Override - protected void tearDown() throws Exception { - if (connection != null) { - connection.close(); - } - super.tearDown(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransientQueueRedeliverTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransientQueueRedeliverTest.java deleted file mode 100644 index dd74ed3fa4..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TransientQueueRedeliverTest.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.activemq.usecases; - -import javax.jms.DeliveryMode; - -/** - * - */ -public class TransientQueueRedeliverTest extends TopicRedeliverTest { - - @Override - protected void setUp() throws Exception { - super.setUp(); - topic = false; - deliveryMode = DeliveryMode.NON_PERSISTENT; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerMessageNotSentToRemoteWhenNoConsumerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerMessageNotSentToRemoteWhenNoConsumerTest.java deleted file mode 100644 index 7a314fef2a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerMessageNotSentToRemoteWhenNoConsumerTest.java +++ /dev/null @@ -1,130 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Destination; -import javax.jms.MessageConsumer; -import java.net.URI; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.util.MessageIdList; - -public class TwoBrokerMessageNotSentToRemoteWhenNoConsumerTest extends JmsMultipleBrokersTestSupport { - - protected static final int MESSAGE_COUNT = 100; - - /** - * BrokerA -> BrokerB - */ - public void testRemoteBrokerHasConsumer() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB"); - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", true); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientB = createConsumer("BrokerB", dest); - - Thread.sleep(2000); - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - - msgsA.waitForMessagesToArrive(MESSAGE_COUNT); - msgsB.waitForMessagesToArrive(MESSAGE_COUNT); - - assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); - assertEquals(MESSAGE_COUNT, msgsB.getMessageCount()); - - } - - /** - * BrokerA -> BrokerB - */ - public void testRemoteBrokerHasNoConsumer() throws Exception { - // Setup broker networks - bridgeBrokers("BrokerA", "BrokerB"); - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", true); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - - msgsA.waitForMessagesToArrive(MESSAGE_COUNT); - - assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); - - } - - /** - * BrokerA -> BrokerB && BrokerB -> BrokerA - */ - public void testDuplexStaticRemoteBrokerHasNoConsumer() throws Exception { - // Setup broker networks - boolean dynamicOnly = true; - int networkTTL = 2; - boolean conduit = true; - bridgeBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduit); - bridgeBrokers("BrokerB", "BrokerA", dynamicOnly, networkTTL, conduit); - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - - Thread.sleep(2 * 1000); - - int messageCount = 2000; - // Send messages - sendMessages("BrokerA", dest, messageCount); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - - msgsA.waitForMessagesToArrive(messageCount); - - assertEquals(messageCount, msgsA.getMessageCount()); - - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=false")); - createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=false")); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerMulticastQueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerMulticastQueueTest.java deleted file mode 100644 index 68c8182a77..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerMulticastQueueTest.java +++ /dev/null @@ -1,271 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.net.URI; -import java.util.Arrays; - -import junit.framework.Test; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.CombinationTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.util.MessageIdList; -import org.apache.activemq.xbean.XBeanBrokerFactory; - -public class TwoBrokerMulticastQueueTest extends CombinationTestSupport { - - public static final int MESSAGE_COUNT = 100; - public static final int BROKER_COUNT = 2; - public static final int CONSUMER_COUNT = 20; - - public String sendUri; - public String recvUri; - private BrokerService[] brokers; - private String groupId; - - public static Test suite() { - return suite(TwoBrokerMulticastQueueTest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - @Override - public void setUp() throws Exception { - groupId = getClass().getName() + "-" + System.currentTimeMillis(); - System.setProperty("groupId", groupId); - super.setAutoFail(true); - super.setUp(); - } - - @Override - public void tearDown() throws Exception { - if (brokers != null) { - for (int i = 0; i < BROKER_COUNT; i++) { - if (brokers[i] != null) { - brokers[i].stop(); - } - } - super.tearDown(); - } - } - - private void doSendReceiveTest() throws Exception { - Destination dest = new ActiveMQQueue("TEST.FOO"); - - ConnectionFactory sendFactory = createConnectionFactory(sendUri); - - Connection conn = createConnection(sendFactory); - sendMessages(conn, dest, MESSAGE_COUNT); - - Thread.sleep(500); - - ConnectionFactory recvFactory = createConnectionFactory(recvUri); - assertEquals(MESSAGE_COUNT, receiveMessages(createConnection(recvFactory), dest, 0)); - } - - private void doMultipleConsumersConnectTest() throws Exception { - Destination dest = new ActiveMQQueue("TEST.FOO"); - - ConnectionFactory sendFactory = createConnectionFactory(sendUri); - - Connection conn = createConnection(sendFactory); - sendMessages(conn, dest, MESSAGE_COUNT); - - Thread.sleep(500); - - ConnectionFactory recvFactory = createConnectionFactory(recvUri); - assertEquals(MESSAGE_COUNT, receiveMessages(createConnection(recvFactory), dest, 0)); - - for (int i = 0; i < (CONSUMER_COUNT - 1); i++) { - assertEquals(0, receiveMessages(createConnection(recvFactory), dest, 200)); - } - } - - public void initCombosForTestSendReceive() { - addCombinationValues("sendUri", new Object[]{"tcp://localhost:61616", "tcp://localhost:61617"}); - addCombinationValues("recvUri", new Object[]{"tcp://localhost:61616", "tcp://localhost:61617"}); - } - - public void testSendReceive() throws Exception { - createMulticastBrokerNetwork(); - doSendReceiveTest(); - } - - public void initCombosForTestMultipleConsumersConnect() { - addCombinationValues("sendUri", new Object[]{"tcp://localhost:61616", "tcp://localhost:61617"}); - addCombinationValues("recvUri", new Object[]{"tcp://localhost:61616", "tcp://localhost:61617"}); - } - - public void testMultipleConsumersConnect() throws Exception { - createMulticastBrokerNetwork(); - doMultipleConsumersConnectTest(); - } - - public void testSendReceiveUsingFailover() throws Exception { - sendUri = "failover:(tcp://localhost:61616,tcp://localhost:61617)"; - recvUri = "failover:(tcp://localhost:61616,tcp://localhost:61617)"; - createMulticastBrokerNetwork(); - doSendReceiveTest(); - } - - public void testMultipleConsumersConnectUsingFailover() throws Exception { - sendUri = "failover:(tcp://localhost:61616,tcp://localhost:61617)"; - recvUri = "failover:(tcp://localhost:61616,tcp://localhost:61617)"; - createMulticastBrokerNetwork(); - doMultipleConsumersConnectTest(); - } - - public void testSendReceiveUsingDiscovery() throws Exception { - sendUri = "discovery:multicast://default?group=" + groupId; - recvUri = "discovery:multicast://default?group=" + groupId; - createMulticastBrokerNetwork(); - doSendReceiveTest(); - } - - public void testMultipleConsumersConnectUsingDiscovery() throws Exception { - sendUri = "discovery:multicast://default?group=" + groupId; - recvUri = "discovery:multicast://default?group=" + groupId; - createMulticastBrokerNetwork(); - doMultipleConsumersConnectTest(); - } - - public void testSendReceiveUsingAutoAssignFailover() throws Exception { - sendUri = "failover:(discovery:multicast:default?group=//" + groupId + ")"; - recvUri = "failover:(discovery:multicast:default?group=//" + groupId + ")"; - createAutoAssignMulticastBrokerNetwork(); - doSendReceiveTest(); - } - - public void testMultipleConsumersConnectUsingAutoAssignFailover() throws Exception { - sendUri = "failover:(discovery:multicast:default?group=//" + groupId + ")"; - recvUri = "failover:(discovery:multicast:default?group=//" + groupId + ")"; - createAutoAssignMulticastBrokerNetwork(); - doMultipleConsumersConnectTest(); - } - - public void testSendReceiveUsingAutoAssignDiscovery() throws Exception { - sendUri = "discovery:multicast://default?group=" + groupId; - recvUri = "discovery:multicast://default?group=" + groupId; - createAutoAssignMulticastBrokerNetwork(); - doSendReceiveTest(); - } - - public void testMultipleConsumersConnectUsingAutoAssignDiscovery() throws Exception { - sendUri = "discovery:multicast://default?group=" + groupId; - recvUri = "discovery:multicast://default?group=" + groupId; - createAutoAssignMulticastBrokerNetwork(); - doMultipleConsumersConnectTest(); - } - - protected void createMulticastBrokerNetwork() throws Exception { - brokers = new BrokerService[BROKER_COUNT]; - for (int i = 0; i < BROKER_COUNT; i++) { - brokers[i] = createBroker("org/apache/activemq/usecases/multicast-broker-" + (i + 1) + ".xml"); - brokers[i].start(); - } - - // Let the brokers discover each other first - Thread.sleep(1000); - } - - protected void createAutoAssignMulticastBrokerNetwork() throws Exception { - brokers = new BrokerService[BROKER_COUNT]; - for (int i = 0; i < BROKER_COUNT; i++) { - brokers[i] = createBroker("org/apache/activemq/usecases/multicast-broker-auto.xml"); - brokers[i].start(); - } - - // Let the brokers discover each other first - Thread.sleep(1000); - } - - protected BrokerService createBroker(String uri) throws Exception { - return (new XBeanBrokerFactory()).createBroker(new URI(uri)); - } - - protected ConnectionFactory createConnectionFactory(String uri) { - return new ActiveMQConnectionFactory(uri); - } - - protected Connection createConnection(ConnectionFactory factory) throws JMSException { - Connection conn = factory.createConnection(); - return conn; - } - - protected int receiveMessages(Connection conn, - Destination dest, - int waitTime) throws JMSException, InterruptedException { - conn.start(); - MessageIdList list = new MessageIdList(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer consumer = sess.createConsumer(dest); - consumer.setMessageListener(list); - - if (waitTime > 0) { - Thread.sleep(waitTime); - } else { - list.waitForMessagesToArrive(MESSAGE_COUNT); - } - - conn.close(); - - return list.getMessageCount(); - } - - protected void sendMessages(Connection conn, Destination dest, int count) throws JMSException { - conn.start(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer prod = sess.createProducer(dest); - - for (int i = 0; i < count; i++) { - prod.send(createTextMessage(sess, "Message " + i, 1024)); - } - - conn.close(); - } - - protected TextMessage createTextMessage(Session session, String initText, int messageSize) throws JMSException { - TextMessage msg = session.createTextMessage(); - - // Pad message text - if (initText.length() < messageSize) { - char[] data = new char[messageSize - initText.length()]; - Arrays.fill(data, '*'); - String str = new String(data); - msg.setText(initText + str); - - // Do not pad message text - } else { - msg.setText(initText); - } - - return msg; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkConnectorWildcardDynamicallyIncludedDestinationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkConnectorWildcardDynamicallyIncludedDestinationTest.java deleted file mode 100644 index 26716acc80..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkConnectorWildcardDynamicallyIncludedDestinationTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.network.NetworkConnector; - -public class TwoBrokerNetworkConnectorWildcardDynamicallyIncludedDestinationTest extends AbstractTwoBrokerNetworkConnectorWildcardIncludedDestinationTestSupport { - - @Override - protected void addIncludedDestination(NetworkConnector nc) { - nc.addExcludedDestination(ActiveMQDestination.createDestination("local.>", ActiveMQDestination.QUEUE_TYPE)); - nc.addExcludedDestination(ActiveMQDestination.createDestination("local.>", ActiveMQDestination.TOPIC_TYPE)); - nc.addExcludedDestination(ActiveMQDestination.createDestination("Consumer.*.local.>", ActiveMQDestination.QUEUE_TYPE)); - nc.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.QUEUE_TYPE)); - nc.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.TOPIC_TYPE)); - nc.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("Consumer.*.global.>", ActiveMQDestination.QUEUE_TYPE)); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkConnectorWildcardStaticallyIncludedDestinationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkConnectorWildcardStaticallyIncludedDestinationTest.java deleted file mode 100644 index 77612fc6db..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkConnectorWildcardStaticallyIncludedDestinationTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.network.NetworkConnector; - -public class TwoBrokerNetworkConnectorWildcardStaticallyIncludedDestinationTest extends AbstractTwoBrokerNetworkConnectorWildcardIncludedDestinationTestSupport { - - @Override - protected void addIncludedDestination(NetworkConnector nc) { - nc.addExcludedDestination(ActiveMQDestination.createDestination("local.>", ActiveMQDestination.QUEUE_TYPE)); - nc.addExcludedDestination(ActiveMQDestination.createDestination("local.>", ActiveMQDestination.TOPIC_TYPE)); - nc.addExcludedDestination(ActiveMQDestination.createDestination("Consumer.*.local.>", ActiveMQDestination.QUEUE_TYPE)); - nc.addStaticallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.QUEUE_TYPE)); - nc.addStaticallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.TOPIC_TYPE)); - nc.addStaticallyIncludedDestination(ActiveMQDestination.createDestination("Consumer.*.global.>", ActiveMQDestination.QUEUE_TYPE)); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkLoadBalanceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkLoadBalanceTest.java deleted file mode 100644 index 7b7000f3f5..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerNetworkLoadBalanceTest.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.activemq.usecases; - -import javax.jms.Destination; -import javax.jms.MessageConsumer; -import java.net.URI; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.util.MessageIdList; -import org.apache.activemq.util.Wait; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class TwoBrokerNetworkLoadBalanceTest extends JmsMultipleBrokersTestSupport { - - protected static final Logger LOG = LoggerFactory.getLogger(TwoBrokerNetworkLoadBalanceTest.class); - - public void testLoadBalancing() throws Exception { - bridgeBrokers("BrokerA", "BrokerB"); - bridgeBrokers("BrokerB", "BrokerA"); - - startAllBrokers(); - waitForBridgeFormation(); - - // Setup destination - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - - // Setup consumers - MessageConsumer clientB = createConsumer("BrokerB", dest); - - // Send messages - sendMessages("BrokerA", dest, 5000); - - // Send messages - sendMessages("BrokerB", dest, 1000); - - // Get message count - final MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - final MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return msgsA.getMessageCount() + msgsB.getMessageCount() == 6000; - } - }); - - LOG.info("A got: " + msgsA.getMessageCount()); - LOG.info("B got: " + msgsB.getMessageCount()); - - assertTrue("B got is fair share: " + msgsB.getMessageCount(), msgsB.getMessageCount() > 2000); - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=false")); - createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=false")); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerQueueClientsReconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerQueueClientsReconnectTest.java deleted file mode 100644 index b8b7bb6046..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerQueueClientsReconnectTest.java +++ /dev/null @@ -1,600 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.Session; -import java.net.URI; -import java.util.Collection; -import java.util.Iterator; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ActiveMQPrefetchPolicy; -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerPlugin; -import org.apache.activemq.broker.BrokerPluginSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.ProducerBrokerExchange; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.network.ConditionalNetworkBridgeFilterFactory; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; -import org.apache.activemq.util.Wait; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class TwoBrokerQueueClientsReconnectTest extends JmsMultipleBrokersTestSupport { - - protected static final int MESSAGE_COUNT = 100; // Best if a factor of 100 - protected static final int PREFETCH_COUNT = 1; - protected static final int NETWORK_PREFETCH = 1; - private static final Logger LOG = LoggerFactory.getLogger(TwoBrokerQueueClientsReconnectTest.class); - - protected int msgsClient1; - protected int msgsClient2; - protected String broker1; - protected String broker2; - - public void testClientAReceivesOnly() throws Exception { - broker1 = "BrokerA"; - broker2 = "BrokerB"; - - doOneClientReceivesOnly(); - } - - public void testClientBReceivesOnly() throws Exception { - broker1 = "BrokerB"; - broker2 = "BrokerA"; - - doOneClientReceivesOnly(); - } - - public void doOneClientReceivesOnly() throws Exception { - // allow immediate replay back to origin - applyRateLimitNetworkFilter(0); - - // Bridge brokers - bridgeBrokers(broker1, broker2); - bridgeBrokers(broker2, broker1); - - // Run brokers - startAllBrokers(); - - // Create queue - Destination dest = createDestination("TEST.FOO", false); - - // Create consumers - MessageConsumer client1 = createConsumer(broker1, dest); - MessageConsumer client2 = createConsumer(broker2, dest); - - // Give clients time to register with broker - Thread.sleep(500); - - // Always send messages to broker A - sendMessages("BrokerA", dest, MESSAGE_COUNT); - - // Close the second client, messages should be sent to the first client - client2.close(); - - // Let the first client receive all messages - msgsClient1 += receiveAllMessages(client1); - client1.close(); - - // First client should have received 100 messages - assertEquals("Client for " + broker1 + " should have receive all messages.", MESSAGE_COUNT, msgsClient1); - } - - public void testClientAReceivesOnlyAfterReconnect() throws Exception { - broker1 = "BrokerA"; - broker2 = "BrokerB"; - - doOneClientReceivesOnlyAfterReconnect(); - } - - public void testClientBReceivesOnlyAfterReconnect() throws Exception { - broker1 = "BrokerB"; - broker2 = "BrokerA"; - - doOneClientReceivesOnlyAfterReconnect(); - } - - public void doOneClientReceivesOnlyAfterReconnect() throws Exception { - // allow immediate replay back to origin - applyRateLimitNetworkFilter(0); - - // Bridge brokers - bridgeBrokers(broker1, broker2); - bridgeBrokers(broker2, broker1); - - // Run brokers - startAllBrokers(); - - // Create queue - Destination dest = createDestination("TEST.FOO", false); - - // Create first consumer - MessageConsumer client1 = createConsumer(broker1, dest); - MessageConsumer client2 = createConsumer(broker2, dest); - - // Give clients time to register with broker - Thread.sleep(500); - - // Always send message to broker A - sendMessages("BrokerA", dest, MESSAGE_COUNT); - - // Let the first client receive the first 20% of messages - msgsClient1 += receiveExactMessages(client1, (int) (MESSAGE_COUNT * 0.20)); - - // Disconnect the first client - client1.close(); - - // Create another client for the first broker - client1 = createConsumer(broker1, dest); - Thread.sleep(500); - - // Close the second client, messages should be sent to the first client - client2.close(); - - // Receive the rest of the messages - msgsClient1 += receiveAllMessages(client1); - client1.close(); - - // The first client should have received 100 messages - assertEquals("Client for " + broker1 + " should have received all messages.", MESSAGE_COUNT, msgsClient1); - } - - public void testTwoClientsReceiveClientADisconnects() throws Exception { - broker1 = "BrokerA"; - broker2 = "BrokerB"; - - doTwoClientsReceiveOneClientDisconnects(); - } - - public void testTwoClientsReceiveClientBDisconnects() throws Exception { - broker1 = "BrokerB"; - broker2 = "BrokerA"; - - doTwoClientsReceiveOneClientDisconnects(); - } - - public void doTwoClientsReceiveOneClientDisconnects() throws Exception { - // ensure all message do not flow across the network too quickly - applyRateLimitNetworkFilter(0.8 * MESSAGE_COUNT); - - // Bridge brokers - bridgeBrokers(broker1, broker2); - bridgeBrokers(broker2, broker1); - - // Run brokers - startAllBrokers(); - - // Create queue - Destination dest = createDestination("TEST.FOO", false); - - // Create first client - MessageConsumer client1 = createConsumer(broker1, dest); - MessageConsumer client2 = createConsumer(broker2, dest); - - // Give clients time to register with broker - Thread.sleep(500); - - // Always send messages to broker A - sendMessages("BrokerA", dest, MESSAGE_COUNT); - - LOG.info("Let each client receive 20% of the messages - 40% total"); - msgsClient1 += receiveExactMessages(client1, (int) (MESSAGE_COUNT * 0.20)); - msgsClient2 += receiveExactMessages(client2, (int) (MESSAGE_COUNT * 0.20)); - - // Disconnect the first client - client1.close(); - - LOG.info("Let the second client receive the rest of the messages"); - msgsClient2 += receiveAllMessages(client2); - client2.close(); - - // First client should have received 20% of the messages - assertEquals("Client for " + broker1 + " should have received 20% of the messages.", (int) (MESSAGE_COUNT * 0.20), msgsClient1); - - // Second client should have received 80% of the messages - assertEquals("Client for " + broker2 + " should have received 80% of the messages.", (int) (MESSAGE_COUNT * 0.80), msgsClient2); - } - - public void testTwoClientsReceiveClientAReconnects() throws Exception { - broker1 = "BrokerA"; - broker2 = "BrokerB"; - - doTwoClientsReceiveOneClientReconnects(); - } - - public void testTwoClientsReceiveClientBReconnects() throws Exception { - broker1 = "BrokerB"; - broker2 = "BrokerA"; - - doTwoClientsReceiveOneClientReconnects(); - } - - public void doTwoClientsReceiveOneClientReconnects() throws Exception { - // ensure all message do not flow across the network too quickly - applyRateLimitNetworkFilter(0.2 * MESSAGE_COUNT); - - // Bridge brokers - bridgeBrokers(broker1, broker2); - bridgeBrokers(broker2, broker1); - - // Run brokers - startAllBrokers(); - - // Create queue - Destination dest = createDestination("TEST.FOO", false); - - // Create the first client - MessageConsumer client1 = createConsumer(broker1, dest); - MessageConsumer client2 = createConsumer(broker2, dest); - - // Give clients time to register with broker - Thread.sleep(500); - - // Always send messages to broker A - sendMessages("BrokerA", dest, MESSAGE_COUNT); - - // Let each client receive 20% of the messages - 40% total - msgsClient1 += receiveExactMessages(client1, (int) (MESSAGE_COUNT * 0.20)); - msgsClient2 += receiveExactMessages(client2, (int) (MESSAGE_COUNT * 0.20)); - - LOG.info("msgsClient1=" + msgsClient1); - LOG.info("msgsClient2=" + msgsClient2); - - Thread.sleep(1000); - LOG.info("Disconnect the first client"); - client1.close(); - - LOG.info("Let the second client receive 20% more of the total messages"); - msgsClient2 += receiveExactMessages(client2, (int) (MESSAGE_COUNT * 0.20)); - - LOG.info("msgsClient2=" + msgsClient2); - - // Create another client for broker 1 - client1 = createConsumer(broker1, dest); - Thread.sleep(1000); - - // Let each client receive 20% of the messages - 40% total - msgsClient1 += receiveExactMessages(client1, (int) (MESSAGE_COUNT * 0.20)); - client1.close(); - LOG.info("new consumer addition, msgsClient1=" + msgsClient1); - - Thread.sleep(2000); - msgsClient2 += receiveExactMessages(client2, (int) (MESSAGE_COUNT * 0.20)); - client2.close(); - LOG.info("msgsClient2=" + msgsClient2); - - // First client should have received 40 messages - assertEquals("Client for " + broker1 + " should have received 40% of the messages.", (int) (MESSAGE_COUNT * 0.40), msgsClient1); - - // Second client should have received 60 messages - assertEquals("Client for " + broker2 + " should have received 60% of the messages.", (int) (MESSAGE_COUNT * 0.60), msgsClient2); - } - - private void applyRateLimitNetworkFilter(double rateLimit) { - ConditionalNetworkBridgeFilterFactory filterFactory = new ConditionalNetworkBridgeFilterFactory(); - filterFactory.setReplayWhenNoConsumers(true); - filterFactory.setRateLimit((int) rateLimit); - filterFactory.setRateDuration(1000); - - Collection brokerList = brokers.values(); - for (Iterator i = brokerList.iterator(); i.hasNext(); ) { - BrokerService broker = i.next().broker; - broker.getDestinationPolicy().getDefaultEntry().setNetworkBridgeFilterFactory(filterFactory); - } - } - - public void testTwoClientsReceiveTwoClientReconnects() throws Exception { - // ensure all message do not flow across the network too quickly - applyRateLimitNetworkFilter(0.5 * MESSAGE_COUNT); - - broker1 = "BrokerA"; - broker2 = "BrokerB"; - - // Bridge brokers - bridgeBrokers(broker1, broker2); - bridgeBrokers(broker2, broker1); - - // Run brokers - startAllBrokers(); - - // Create queue - Destination dest = createDestination("TEST.FOO", false); - - // Create the first client - MessageConsumer client1 = createConsumer(broker1, dest); - MessageConsumer client2 = createConsumer(broker2, dest); - - // Give clients time to register with broker - Thread.sleep(500); - - // Always send messages to broker A - sendMessages("BrokerA", dest, MESSAGE_COUNT); - - // Let each client receive 20% of the messages - 40% total - msgsClient1 += receiveExactMessages(client1, (int) (MESSAGE_COUNT * 0.20)); - msgsClient2 += receiveExactMessages(client2, (int) (MESSAGE_COUNT * 0.20)); - - LOG.info("Disconnect both clients"); - client1.close(); - client2.close(); - - // Let each client receive 30% more of the total messages - 60% total - LOG.info("Serially create another two clients for each broker and consume in turn"); - client1 = createConsumer(broker1, dest); - msgsClient1 += receiveExactMessages(client1, (int) (MESSAGE_COUNT * 0.30)); - client1.close(); - - // the close will allow replay or the replay of the remaining messages - client2 = createConsumer(broker2, dest); - msgsClient2 += receiveExactMessages(client2, (int) (MESSAGE_COUNT * 0.30)); - client2.close(); - - // First client should have received 50% of the messages - assertEquals("Client for " + broker1 + " should have received 50% of the messages.", (int) (MESSAGE_COUNT * 0.50), msgsClient1); - - // Second client should have received 50% of the messages - assertEquals("Client for " + broker2 + " should have received 50% of the messages.", (int) (MESSAGE_COUNT * 0.50), msgsClient2); - } - - public void testDuplicateSend() throws Exception { - broker1 = "BrokerA"; - broker2 = "BrokerB"; - - // enable producer audit for the network connector, off by default b/c of interference with composite - // dests and virtual topics - brokers.get(broker2).broker.getTransportConnectors().get(0).setAuditNetworkProducers(true); - bridgeBrokers(broker1, broker2); - - final AtomicBoolean first = new AtomicBoolean(); - final CountDownLatch gotMessageLatch = new CountDownLatch(1); - - BrokerService brokerService = brokers.get(broker2).broker; - brokerService.setPersistent(true); - brokerService.setDeleteAllMessagesOnStartup(true); - brokerService.setPlugins(new BrokerPlugin[]{new BrokerPluginSupport() { - @Override - public void send(final ProducerBrokerExchange producerExchange, - org.apache.activemq.command.Message messageSend) throws Exception { - super.send(producerExchange, messageSend); - if (first.compareAndSet(false, true)) { - producerExchange.getConnectionContext().setDontSendReponse(true); - new Thread() { - @Override - public void run() { - try { - LOG.info("Waiting for recepit"); - assertTrue("message received on time", gotMessageLatch.await(60, TimeUnit.SECONDS)); - LOG.info("Stopping connection post send and receive and multiple producers"); - producerExchange.getConnectionContext().getConnection().stop(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }.start(); - } - } - }}); - - // Run brokers - startAllBrokers(); - - waitForBridgeFormation(); - - // Create queue - Destination dest = createDestination("TEST.FOO", false); - - MessageConsumer client2 = createConsumer(broker2, dest); - - sendMessages("BrokerA", dest, 1); - - assertEquals("Client got message", 1, receiveExactMessages(client2, 1)); - client2.close(); - gotMessageLatch.countDown(); - - // message still pending on broker1 - assertEquals("messages message still there", 1, brokers.get(broker1).broker.getAdminView().getTotalMessageCount()); - - client2 = createConsumer(broker2, dest); - - LOG.info("Let the second client receive the rest of the messages"); - assertEquals("no duplicate message", 0, receiveAllMessages(client2)); - assertEquals("no duplicate message", 0, receiveAllMessages(client2)); - - assertEquals("no messages enqueued", 0, brokers.get(broker2).broker.getAdminView().getTotalMessageCount()); - assertTrue("no messages enqueued on origin", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 0 == brokers.get(broker1).broker.getAdminView().getTotalMessageCount(); - } - })); - } - - public void testDuplicateSendWithNoAuditEnqueueCountStat() throws Exception { - broker1 = "BrokerA"; - broker2 = "BrokerB"; - - NetworkConnector networkConnector = bridgeBrokers(broker1, broker2); - - final AtomicBoolean first = new AtomicBoolean(); - final CountDownLatch gotMessageLatch = new CountDownLatch(1); - - BrokerService brokerService = brokers.get(broker2).broker; - brokerService.setPersistent(true); - brokerService.setDeleteAllMessagesOnStartup(true); - // disable concurrent dispatch otherwise store duplicate suppression will be skipped b/c cursor audit is already - // disabled so verification of stats will fail - ie: duplicate will be dispatched - ((KahaDBPersistenceAdapter) brokerService.getPersistenceAdapter()).setConcurrentStoreAndDispatchQueues(false); - brokerService.setPlugins(new BrokerPlugin[]{new BrokerPluginSupport() { - @Override - public void send(final ProducerBrokerExchange producerExchange, - org.apache.activemq.command.Message messageSend) throws Exception { - super.send(producerExchange, messageSend); - if (first.compareAndSet(false, true)) { - producerExchange.getConnectionContext().setDontSendReponse(true); - new Thread() { - @Override - public void run() { - try { - LOG.info("Waiting for recepit"); - assertTrue("message received on time", gotMessageLatch.await(60, TimeUnit.SECONDS)); - LOG.info("Stopping connection post send and receive and multiple producers"); - producerExchange.getConnectionContext().getConnection().stop(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }.start(); - } - } - }}); - - // Create queue - ActiveMQDestination dest = createDestination("TEST.FOO", false); - - // statically include our destination - networkConnector.addStaticallyIncludedDestination(dest); - - // Run brokers - startAllBrokers(); - - waitForBridgeFormation(); - - sendMessages("BrokerA", dest, 1); - - // wait for broker2 to get the initial forward - Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return brokers.get(broker2).broker.getAdminView().getTotalMessageCount() == 1; - } - }); - - // message still pending on broker1 - assertEquals("messages message still there", 1, brokers.get(broker1).broker.getAdminView().getTotalMessageCount()); - - // allow the bridge to be shutdown and restarted - gotMessageLatch.countDown(); - - // verify message is forwarded after restart - assertTrue("no messages enqueued on origin", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - return 0 == brokers.get(broker1).broker.getAdminView().getTotalMessageCount(); - } - })); - - assertEquals("one messages pending", 1, brokers.get(broker2).broker.getAdminView().getTotalMessageCount()); - assertEquals("one messages enqueued", 1, brokers.get(broker2).broker.getDestination(dest).getDestinationStatistics().getEnqueues().getCount()); - } - - protected int receiveExactMessages(MessageConsumer consumer, int msgCount) throws Exception { - Message msg; - int i; - for (i = 0; i < msgCount; i++) { - msg = consumer.receive(4000); - if (msg == null) { - LOG.error("Consumer failed to receive exactly " + msgCount + " messages. Actual messages received is: " + i); - break; - } - } - - return i; - } - - protected int receiveAllMessages(MessageConsumer consumer) throws Exception { - int msgsReceived = 0; - - Message msg; - do { - msg = consumer.receive(1000); - if (msg != null) { - msgsReceived++; - } - } while (msg != null); - - return msgsReceived; - } - - @Override - protected MessageConsumer createConsumer(String brokerName, Destination dest) throws Exception { - Connection conn = createConnection(brokerName); - conn.start(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - return sess.createConsumer(dest); - } - - @Override - protected void configureBroker(BrokerService broker) { - PolicyMap policyMap = new PolicyMap(); - PolicyEntry defaultEntry = new PolicyEntry(); - defaultEntry.setEnableAudit(false); - policyMap.setDefaultEntry(defaultEntry); - broker.setDestinationPolicy(policyMap); - } - - @Override - protected NetworkConnector bridgeBrokers(BrokerService localBroker, - BrokerService remoteBroker, - boolean dynamicOnly, - int networkTTL, - boolean conduit, - boolean failover) throws Exception { - NetworkConnector nc = super.bridgeBrokers(localBroker, remoteBroker, dynamicOnly, networkTTL, conduit, failover); - nc.setPrefetchSize(NETWORK_PREFETCH); - nc.setDecreaseNetworkConsumerPriority(true); - return nc; - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - createBroker(new URI("broker:(tcp://localhost:61616)/BrokerA?persistent=false&useJmx=true")); - createBroker(new URI("broker:(tcp://localhost:61617)/BrokerB?persistent=false&useJmx=true")); - - // Configure broker connection factory - ActiveMQConnectionFactory factoryA; - ActiveMQConnectionFactory factoryB; - factoryA = (ActiveMQConnectionFactory) getConnectionFactory("BrokerA"); - factoryB = (ActiveMQConnectionFactory) getConnectionFactory("BrokerB"); - - // Set prefetch policy - ActiveMQPrefetchPolicy policy = new ActiveMQPrefetchPolicy(); - policy.setAll(PREFETCH_COUNT); - - factoryA.setPrefetchPolicy(policy); - factoryB.setPrefetchPolicy(policy); - - msgsClient1 = 0; - msgsClient2 = 0; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerQueueSendReceiveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerQueueSendReceiveTest.java deleted file mode 100644 index 524af21a59..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerQueueSendReceiveTest.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.activemq.usecases; - -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.network.DemandForwardingBridgeSupport; -import org.apache.activemq.util.Wait; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class TwoBrokerQueueSendReceiveTest extends TwoBrokerTopicSendReceiveTest { - - private static final Logger LOG = LoggerFactory.getLogger(TwoBrokerQueueSendReceiveTest.class); - - @Override - protected void setUp() throws Exception { - topic = false; - super.setUp(); - } - - public void testReceiveOnXConsumersNoLeak() throws Exception { - consumer.close(); - sendMessages(); - for (int i = 0; i < data.length; i++) { - consumer = createConsumer(); - onMessage(consumer.receive(10000)); - consumer.close(); - } - waitForMessagesToBeDelivered(); - assertEquals("Got all messages", data.length, messages.size()); - - BrokerService broker = brokers.get("receiver"); - final DemandForwardingBridgeSupport bridge = (DemandForwardingBridgeSupport) broker.getNetworkConnectors().get(0).activeBridges().toArray()[0]; - assertTrue("No extra, size:" + bridge.getLocalSubscriptionMap().size(), Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("local subs map size = " + bridge.getLocalSubscriptionMap().size()); - return 0 == bridge.getLocalSubscriptionMap().size(); - } - })); - - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTempQueueAdvisoryTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTempQueueAdvisoryTest.java deleted file mode 100644 index 05aa3e42fd..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTempQueueAdvisoryTest.java +++ /dev/null @@ -1,212 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TemporaryQueue; -import javax.management.ObjectName; -import java.net.URI; - -import junit.framework.Test; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.ActiveMQMessageConsumer; -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.broker.jmx.DestinationViewMBean; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.util.Wait; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class TwoBrokerTempQueueAdvisoryTest extends JmsMultipleBrokersTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(TwoBrokerTempQueueAdvisoryTest.class); - - private void sendReceiveTempQueueMessage(String broker) throws Exception { - - ConnectionFactory factory = getConnectionFactory(broker); - Connection conn = factory.createConnection(); - Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - session.createTemporaryQueue(); - conn.close(); - } - - public void testTemporaryQueueAdvisory() throws Exception { - LOG.info("Running testTemporaryQueueAdvisory()"); - - bridgeBrokers("BrokerA", "BrokerB"); - bridgeBrokers("BrokerB", "BrokerA"); - - startAllBrokers(); - waitForBridgeFormation(); - waitForMinTopicRegionConsumerCount("BrokerB", 1); - waitForMinTopicRegionConsumerCount("BrokerA", 1); - - final int iterations = 30; - for (int i = 0; i < iterations; i++) { - sendReceiveTempQueueMessage("BrokerA"); - } - - waitForMinTopicRegionConsumerCount("BrokerB", 1); - waitForMinTopicRegionConsumerCount("BrokerA", 1); - - final DestinationViewMBean brokerAView = createView("BrokerA", "ActiveMQ.Advisory.TempQueue", ActiveMQDestination.TOPIC_TYPE); - assertTrue("exact amount of advisories created on A, one each for creation/deletion", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("BrokerA temp advisory enque count: " + brokerAView.getEnqueueCount()); - return iterations * 2 == brokerAView.getEnqueueCount(); - } - })); - - final DestinationViewMBean brokerBView = createView("BrokerB", "ActiveMQ.Advisory.TempQueue", ActiveMQDestination.TOPIC_TYPE); - assertTrue("exact amount of advisories created on B, one each for creation/deletion", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("BrokerB temp advisory enque count: " + brokerBView.getEnqueueCount()); - return iterations * 2 == brokerBView.getEnqueueCount(); - } - })); - } - - public boolean useDuplex = true; - - public void initCombosForTestSendToRemovedTemp() { - addCombinationValues("useDuplex", new Boolean[]{Boolean.FALSE, Boolean.TRUE}); - } - - public void testSendToRemovedTemp() throws Exception { - - ActiveMQQueue requestReplyDest = new ActiveMQQueue("RequestReply"); - - NetworkConnector nc = bridgeBrokers("BrokerA", "BrokerB"); - if (useDuplex) { - nc.setDuplex(true); - } else { - bridgeBrokers("BrokerB", "BrokerA"); - } - - // destination advisory can loose the race with message dispatch, so we need to allow replies on network broker - // to work in the absence of an advisory, the destination will be cleaned up in the normal - // way - if (!useDuplex) { - brokers.get("BrokerB").broker.setAllowTempAutoCreationOnSend(true); - } - - TransportConnector forClient = brokers.get("BrokerA").broker.addConnector("tcp://localhost:0"); - startAllBrokers(); - waitForBridgeFormation(); - waitForMinTopicRegionConsumerCount("BrokerB", 1); - waitForMinTopicRegionConsumerCount("BrokerA", 1); - - ConnectionFactory factory = new ActiveMQConnectionFactory(forClient.getConnectUri()); - ActiveMQConnection conn = (ActiveMQConnection) factory.createConnection(); - conn.setWatchTopicAdvisories(false); - conn.start(); - Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - - ConnectionFactory replyFactory = getConnectionFactory("BrokerB"); - for (int i = 0; i < 500; i++) { - TemporaryQueue tempDest = session.createTemporaryQueue(); - MessageProducer producer = session.createProducer(requestReplyDest); - javax.jms.Message message = session.createTextMessage("req-" + i); - message.setJMSReplyTo(tempDest); - - ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session.createConsumer(tempDest); - producer.send(message); - - ActiveMQConnection replyConnection = (ActiveMQConnection) replyFactory.createConnection(); - replyConnection.setWatchTopicAdvisories(false); - replyConnection.start(); - Session replySession = replyConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQMessageConsumer replyConsumer = (ActiveMQMessageConsumer) replySession.createConsumer(requestReplyDest); - javax.jms.Message msg = replyConsumer.receive(10000); - assertNotNull("request message not null: " + i, msg); - MessageProducer replyProducer = replySession.createProducer(msg.getJMSReplyTo()); - replyProducer.send(session.createTextMessage("reply-" + i)); - replyConnection.close(); - - javax.jms.Message reply = consumer.receive(10000); - assertNotNull("reply message : " + i + ", to: " + tempDest + ", by consumer:" + consumer.getConsumerId(), reply); - consumer.close(); - tempDest.delete(); - } - } - - protected DestinationViewMBean createView(String broker, String destination, byte type) throws Exception { - String domain = "org.apache.activemq"; - ObjectName name; - if (type == ActiveMQDestination.QUEUE_TYPE) { - name = new ObjectName(domain + ":type=Broker,brokerName=" + broker + ",destinationType=Queue,destinationName=" + destination); - } else { - name = new ObjectName(domain + ":type=Broker,brokerName=" + broker + ",destinationType=Topic,destinationName=" + destination); - } - return (DestinationViewMBean) brokers.get(broker).broker.getManagementContext().newProxyInstance(name, DestinationViewMBean.class, true); - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - - String options = new String("?persistent=false"); - createBroker(new URI("broker:(tcp://localhost:0)/BrokerA" + options)); - createBroker(new URI("broker:(tcp://localhost:0)/BrokerB" + options)); - } - - public static Test suite() { - return suite(TwoBrokerTempQueueAdvisoryTest.class); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveLotsOfMessagesUsingTcpTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveLotsOfMessagesUsingTcpTest.java deleted file mode 100644 index 8cf04f8379..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveLotsOfMessagesUsingTcpTest.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.activemq.usecases; - -/** - * - */ -public class TwoBrokerTopicSendReceiveLotsOfMessagesUsingTcpTest extends TwoBrokerTopicSendReceiveUsingTcpTest { - - @Override - protected void setUp() throws Exception { - this.messageCount = 5000; - super.setUp(); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveTest.java deleted file mode 100644 index 1969f31ed1..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveTest.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.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.JMSException; -import java.util.HashMap; -import java.util.Iterator; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.test.JmsTopicSendReceiveWithTwoConnectionsTest; -import org.apache.activemq.util.ServiceSupport; -import org.apache.activemq.xbean.BrokerFactoryBean; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.ClassPathResource; - -/** - * - */ -public class TwoBrokerTopicSendReceiveTest extends JmsTopicSendReceiveWithTwoConnectionsTest { - - private static final Logger LOG = LoggerFactory.getLogger(TwoBrokerTopicSendReceiveTest.class); - - protected ActiveMQConnectionFactory sendFactory; - protected ActiveMQConnectionFactory receiveFactory; - protected HashMap brokers = new HashMap<>(); - - @Override - protected void setUp() throws Exception { - sendFactory = createSenderConnectionFactory(); - receiveFactory = createReceiverConnectionFactory(); - - // Give server enough time to setup, - // so we don't lose messages when connection fails - LOG.info("Waiting for brokers Initialize."); - Thread.sleep(5000); - LOG.info("Brokers should be initialized by now.. starting test."); - - super.setUp(); - } - - protected ActiveMQConnectionFactory createReceiverConnectionFactory() throws JMSException { - return createConnectionFactory("org/apache/activemq/usecases/receiver.xml", "receiver", "vm://receiver"); - } - - protected ActiveMQConnectionFactory createSenderConnectionFactory() throws JMSException { - return createConnectionFactory("org/apache/activemq/usecases/sender.xml", "sender", "vm://sender"); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - for (Iterator iter = brokers.values().iterator(); iter.hasNext(); ) { - BrokerService broker = iter.next(); - ServiceSupport.dispose(broker); - iter.remove(); - } - } - - @Override - protected Connection createReceiveConnection() throws JMSException { - return receiveFactory.createConnection(); - } - - @Override - protected Connection createSendConnection() throws JMSException { - return sendFactory.createConnection(); - } - - protected ActiveMQConnectionFactory createConnectionFactory(String config, - String brokerName, - String connectUrl) throws JMSException { - try { - BrokerFactoryBean brokerFactory = new BrokerFactoryBean(new ClassPathResource(config)); - brokerFactory.afterPropertiesSet(); - BrokerService broker = brokerFactory.getBroker(); - brokers.put(brokerName, broker); - - return new ActiveMQConnectionFactory(connectUrl); - - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveUsingJavaConfigurationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveUsingJavaConfigurationTest.java deleted file mode 100644 index 75141f25ec..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveUsingJavaConfigurationTest.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.activemq.usecases; - -import javax.jms.JMSException; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; - -/** - * - */ -public class TwoBrokerTopicSendReceiveUsingJavaConfigurationTest extends TwoBrokerTopicSendReceiveTest { - - BrokerService receiveBroker; - BrokerService sendBroker; - - @Override - protected ActiveMQConnectionFactory createReceiverConnectionFactory() throws JMSException { - try { - receiveBroker = new BrokerService(); - receiveBroker.setBrokerName("receiveBroker"); - receiveBroker.setUseJmx(false); - receiveBroker.setPersistent(false); - receiveBroker.addConnector("tcp://localhost:62002"); - receiveBroker.addNetworkConnector("static:failover:tcp://localhost:62001"); - receiveBroker.start(); - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:62002"); - return factory; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - @Override - protected ActiveMQConnectionFactory createSenderConnectionFactory() throws JMSException { - try { - sendBroker = new BrokerService(); - sendBroker.setBrokerName("sendBroker"); - sendBroker.setUseJmx(false); - sendBroker.setPersistent(false); - sendBroker.addConnector("tcp://localhost:62001"); - sendBroker.addNetworkConnector("static:failover:tcp://localhost:62002"); - sendBroker.start(); - - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:62001"); - return factory; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - if (sendBroker != null) { - sendBroker.stop(); - } - if (receiveBroker != null) { - receiveBroker.stop(); - } - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveUsingTcpTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveUsingTcpTest.java deleted file mode 100644 index 5fdf4fa043..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveUsingTcpTest.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.activemq.usecases; - -import javax.jms.JMSException; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.xbean.BrokerFactoryBean; -import org.springframework.core.io.ClassPathResource; - -/** - * - */ -public class TwoBrokerTopicSendReceiveUsingTcpTest extends TwoBrokerTopicSendReceiveTest { - - private BrokerService receiverBroker; - private BrokerService senderBroker; - - @Override - protected void setUp() throws Exception { - BrokerFactoryBean brokerFactory; - - brokerFactory = new BrokerFactoryBean(new ClassPathResource("org/apache/activemq/usecases/receiver.xml")); - brokerFactory.afterPropertiesSet(); - receiverBroker = brokerFactory.getBroker(); - - brokerFactory = new BrokerFactoryBean(new ClassPathResource("org/apache/activemq/usecases/sender.xml")); - brokerFactory.afterPropertiesSet(); - senderBroker = brokerFactory.getBroker(); - - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - - if (receiverBroker != null) { - receiverBroker.stop(); - } - if (senderBroker != null) { - senderBroker.stop(); - } - } - - @Override - protected ActiveMQConnectionFactory createReceiverConnectionFactory() throws JMSException { - try { - ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(receiverBroker.getTransportConnectors().get(0).getConnectUri()); - return fac; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - @Override - protected ActiveMQConnectionFactory createSenderConnectionFactory() throws JMSException { - try { - ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(senderBroker.getTransportConnectors().get(0).getConnectUri()); - return fac; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerVirtualDestDinamicallyIncludedDestTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerVirtualDestDinamicallyIncludedDestTest.java deleted file mode 100644 index cb7cf15fb4..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerVirtualDestDinamicallyIncludedDestTest.java +++ /dev/null @@ -1,231 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Destination; -import javax.jms.MessageConsumer; -import java.io.File; -import java.io.IOException; -import java.net.URI; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.DestinationInterceptor; -import org.apache.activemq.broker.region.virtual.VirtualDestination; -import org.apache.activemq.broker.region.virtual.VirtualDestinationInterceptor; -import org.apache.activemq.broker.region.virtual.VirtualTopic; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.store.kahadb.KahaDBStore; -import org.apache.activemq.util.MessageIdList; - -public class TwoBrokerVirtualDestDinamicallyIncludedDestTest extends JmsMultipleBrokersTestSupport { - - protected static final int MESSAGE_COUNT = 10; - boolean dynamicOnly = true; - int networkTTL = 1; - boolean conduit = true; - boolean suppressDuplicateQueueSubscriptions = true; - boolean decreaseNetworkConsumerPriority = true; - - /** - * BrokerA -> BrokerB && BrokerB -> BrokerA - */ - public void testTopicDinamicallyIncludedBehavior() throws Exception { - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("test", true); - - // Setup consumers - MessageConsumer clientA = createConsumer("BrokerA", dest); - MessageConsumer clientB = createConsumer("BrokerB", dest); - - Thread.sleep(2 * 1000); - - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - - // Get message count - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - msgsA.waitForMessagesToArrive(MESSAGE_COUNT); - assertEquals(MESSAGE_COUNT, msgsA.getMessageCount()); - - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - msgsB.waitForMessagesToArrive(MESSAGE_COUNT); - assertEquals(0, msgsB.getMessageCount()); - - } - - /** - * BrokerA -> BrokerB && BrokerB -> BrokerA - */ - public void testVirtualDestinationsDinamicallyIncludedBehavior1() throws Exception { - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("global.test", true); - - // Setup consumers - MessageConsumer clientB1 = createConsumer("BrokerB", dest); - MessageConsumer clientB2 = createConsumer("BrokerB", createDestination("Consumer.foo-bar.global.test", false)); - - Thread.sleep(2 * 1000); - - int messageCount = MESSAGE_COUNT; - // Send messages - sendMessages("BrokerA", dest, messageCount); - - // Get message count - MessageIdList msgsB1 = getConsumerMessages("BrokerB", clientB1); - msgsB1.waitForMessagesToArrive(messageCount); - assertEquals(messageCount, msgsB1.getMessageCount()); - - MessageIdList msgsB2 = getConsumerMessages("BrokerB", clientB2); - msgsB2.waitForMessagesToArrive(messageCount); - assertEquals(messageCount, msgsB2.getMessageCount()); - - } - - /** - * BrokerA -> BrokerB && BrokerB -> BrokerA - */ - public void testVirtualDestinationsDinamicallyIncludedBehavior2() throws Exception { - - startAllBrokers(); - - // Setup destination - Destination dest = createDestination("global.test", true); - - // Setup consumers - //MessageConsumer clientB1 = createConsumer("BrokerB", dest); - MessageConsumer clientB2 = createConsumer("BrokerB", createDestination("Consumer.foo-bar.global.test", false)); - - Thread.sleep(2 * 1000); - - // Send messages - sendMessages("BrokerA", dest, MESSAGE_COUNT); - - // Get message count - MessageIdList msgsB2 = getConsumerMessages("BrokerB", clientB2); - msgsB2.waitForMessagesToArrive(MESSAGE_COUNT); - assertEquals(MESSAGE_COUNT, msgsB2.getMessageCount()); - - } - - /** - * BrokerA -> BrokerB && BrokerB -> BrokerA - */ - public void testVirtualDestinationsDinamicallyIncludedBehavior3() throws Exception { - final String topic = "global.test"; - final String vq = "Consumer.foo." + topic; - - startAllBrokers(); - final int msgs1 = 1001; - final int msgs2 = 1456; - - // Setup destination - Destination tDest = createDestination(topic, true); - Destination vqDest = createDestination(vq, false); - - // Setup consumers - MessageConsumer clientB1t = createConsumer("BrokerA", tDest); - MessageConsumer clientB2t = createConsumer("BrokerB", tDest); - MessageConsumer clientB1vq = createConsumer("BrokerA", vqDest); - - Thread.sleep(2 * 1000); - - // Send messages - sendMessages("BrokerA", tDest, msgs1); - sendMessages("BrokerB", tDest, msgs2); - - Thread.sleep(5000); - - // Get message count - MessageIdList msgsB1t = getConsumerMessages("BrokerA", clientB1t); - msgsB1t.waitForMessagesToArrive(msgs1 + msgs2); - assertEquals(msgs1 + msgs2, msgsB1t.getMessageCount()); - MessageIdList msgsB2t = getConsumerMessages("BrokerB", clientB2t); - msgsB2t.waitForMessagesToArrive(msgs1 + msgs2); - assertEquals(msgs1 + msgs2, msgsB2t.getMessageCount()); - MessageIdList msgsB1vq = getConsumerMessages("BrokerA", clientB1vq); - msgsB1vq.waitForMessagesToArrive(msgs1 + msgs2); - assertEquals(msgs1 + msgs2, msgsB1vq.getMessageCount()); - - assertEquals(0, getQueueSize("BrokerA", (ActiveMQDestination) vqDest)); - assertEquals(0, getQueueSize("BrokerB", (ActiveMQDestination) vqDest)); - destroyAllBrokers(); - } - - public long getQueueSize(String broker, ActiveMQDestination destination) throws Exception { - BrokerItem bi = brokers.get(broker); - return bi.broker.getDestination(destination).getDestinationStatistics().getMessages().getCount(); - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - String options = new String("?useJmx=false&deleteAllMessagesOnStartup=true"); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61616)/BrokerA" + options)); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61617)/BrokerB" + options)); - - // Setup broker networks - NetworkConnector nc1 = bridgeBrokers("BrokerA", "BrokerB", dynamicOnly, networkTTL, conduit); - nc1.setDecreaseNetworkConsumerPriority(decreaseNetworkConsumerPriority); - nc1.setSuppressDuplicateQueueSubscriptions(suppressDuplicateQueueSubscriptions); - nc1.addStaticallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.TOPIC_TYPE)); - //nc1.addExcludedDestination(ActiveMQDestination.createDestination("Consumer.*.global.>", ActiveMQDestination.QUEUE_TYPE)); - nc1.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.QUEUE_TYPE)); - nc1.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.TOPIC_TYPE)); - nc1.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("Consumer.*.global.>", ActiveMQDestination.QUEUE_TYPE)); - - NetworkConnector nc2 = bridgeBrokers("BrokerB", "BrokerA", dynamicOnly, networkTTL, conduit); - nc2.setDecreaseNetworkConsumerPriority(decreaseNetworkConsumerPriority); - nc2.setSuppressDuplicateQueueSubscriptions(suppressDuplicateQueueSubscriptions); - nc2.addStaticallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.TOPIC_TYPE)); - //nc2.addExcludedDestination(ActiveMQDestination.createDestination("Consumer.*.global.>", ActiveMQDestination.QUEUE_TYPE)); - nc2.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.QUEUE_TYPE)); - nc2.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("global.>", ActiveMQDestination.TOPIC_TYPE)); - nc2.addDynamicallyIncludedDestination(ActiveMQDestination.createDestination("Consumer.*.global.>", ActiveMQDestination.QUEUE_TYPE)); - } - - private BrokerService createAndConfigureBroker(URI uri) throws Exception { - BrokerService broker = createBroker(uri); - - configurePersistenceAdapter(broker); - - // make all topics virtual and consumers use the default prefix - VirtualDestinationInterceptor virtualDestinationInterceptor = new VirtualDestinationInterceptor(); - VirtualTopic vTopic = new VirtualTopic(); - vTopic.setLocal(true); - virtualDestinationInterceptor.setVirtualDestinations(new VirtualDestination[]{vTopic}); - DestinationInterceptor[] destinationInterceptors = new DestinationInterceptor[]{virtualDestinationInterceptor}; - broker.setDestinationInterceptors(destinationInterceptors); - return broker; - } - - protected void configurePersistenceAdapter(BrokerService broker) throws IOException { - File dataFileDir = new File("target/test-amq-data/kahadb/" + broker.getBrokerName()); - KahaDBStore kaha = new KahaDBStore(); - kaha.setDirectory(dataFileDir); - kaha.deleteAllMessages(); - broker.setPersistenceAdapter(kaha); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerVirtualTopicForwardingTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerVirtualTopicForwardingTest.java deleted file mode 100644 index d78322d385..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoBrokerVirtualTopicForwardingTest.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.activemq.usecases; - -import javax.jms.MessageConsumer; -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.util.LinkedList; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.Destination; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.store.kahadb.KahaDBStore; -import org.apache.activemq.util.MessageIdList; - -import static org.apache.activemq.TestSupport.getDestination; - -/** - * @author Christian Posta - */ -public class TwoBrokerVirtualTopicForwardingTest extends JmsMultipleBrokersTestSupport { - - public void testBridgeVirtualTopicQueues() throws Exception { - - bridgeAndConfigureBrokers("BrokerA", "BrokerB"); - startAllBrokers(); - waitForBridgeFormation(); - - MessageConsumer clientA = createConsumer("BrokerA", createDestination("Consumer.A.VirtualTopic.tempTopic", false)); - MessageConsumer clientB = createConsumer("BrokerB", createDestination("Consumer.B.VirtualTopic.tempTopic", false)); - - // give a sec to let advisories propagate - Thread.sleep(500); - - ActiveMQQueue queueA = new ActiveMQQueue("Consumer.A.VirtualTopic.tempTopic"); - Destination destination = getDestination(brokers.get("BrokerA").broker, queueA); - assertEquals(1, destination.getConsumers().size()); - - ActiveMQQueue queueB = new ActiveMQQueue("Consumer.B.VirtualTopic.tempTopic"); - destination = getDestination(brokers.get("BrokerA").broker, queueB); - assertEquals(1, destination.getConsumers().size()); - - ActiveMQTopic virtualTopic = new ActiveMQTopic("VirtualTopic.tempTopic"); - assertNull(getDestination(brokers.get("BrokerA").broker, virtualTopic)); - assertNull(getDestination(brokers.get("BrokerB").broker, virtualTopic)); - - // send some messages - sendMessages("BrokerA", virtualTopic, 1); - - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - - msgsA.waitForMessagesToArrive(1); - msgsB.waitForMessagesToArrive(1); - - // ensure we don't get any more messages - Thread.sleep(2000); - - assertEquals(1, msgsA.getMessageCount()); - assertEquals(1, msgsB.getMessageCount()); - - } - - public void testDontBridgeQueuesWithOnlyQueueConsumers() throws Exception { - dontBridgeVirtualTopicConsumerQueues("BrokerA", "BrokerB"); - - startAllBrokers(); - waitForBridgeFormation(); - - MessageConsumer clientA = createConsumer("BrokerA", createDestination("Consumer.A.VirtualTopic.tempTopic", false)); - MessageConsumer clientB = createConsumer("BrokerB", createDestination("Consumer.B.VirtualTopic.tempTopic", false)); - - // give a sec to let advisories propagate - Thread.sleep(500); - - ActiveMQQueue queueA = new ActiveMQQueue("Consumer.A.VirtualTopic.tempTopic"); - Destination destination = getDestination(brokers.get("BrokerA").broker, queueA); - assertEquals(1, destination.getConsumers().size()); - - ActiveMQQueue queueB = new ActiveMQQueue("Consumer.B.VirtualTopic.tempTopic"); - destination = getDestination(brokers.get("BrokerA").broker, queueB); - assertNull(destination); - - ActiveMQTopic virtualTopic = new ActiveMQTopic("VirtualTopic.tempTopic"); - assertNull(getDestination(brokers.get("BrokerA").broker, virtualTopic)); - assertNull(getDestination(brokers.get("BrokerB").broker, virtualTopic)); - - // send some messages - sendMessages("BrokerA", virtualTopic, 1); - - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - - msgsA.waitForMessagesToArrive(1); - msgsB.waitForMessagesToArrive(0); - - // ensure we don't get any more messages - Thread.sleep(2000); - - assertEquals(1, msgsA.getMessageCount()); - assertEquals(0, msgsB.getMessageCount()); - } - - public void testDontBridgeQueuesWithBothTypesConsumers() throws Exception { - dontBridgeVirtualTopicConsumerQueues("BrokerA", "BrokerB"); - - startAllBrokers(); - waitForBridgeFormation(); - - MessageConsumer clientA = createConsumer("BrokerA", createDestination("Consumer.A.VirtualTopic.tempTopic", false)); - MessageConsumer clientB = createConsumer("BrokerB", createDestination("Consumer.B.VirtualTopic.tempTopic", false)); - MessageConsumer clientC = createConsumer("BrokerB", createDestination("VirtualTopic.tempTopic", true)); - - // give a sec to let advisories propagate - Thread.sleep(500); - - ActiveMQQueue queueA = new ActiveMQQueue("Consumer.A.VirtualTopic.tempTopic"); - Destination destination = getDestination(brokers.get("BrokerA").broker, queueA); - assertEquals(1, destination.getConsumers().size()); - - ActiveMQQueue queueB = new ActiveMQQueue("Consumer.B.VirtualTopic.tempTopic"); - destination = getDestination(brokers.get("BrokerA").broker, queueB); - assertNull(destination); - - ActiveMQTopic virtualTopic = new ActiveMQTopic("VirtualTopic.tempTopic"); - assertNotNull(getDestination(brokers.get("BrokerA").broker, virtualTopic)); - assertNotNull(getDestination(brokers.get("BrokerB").broker, virtualTopic)); - - // send some messages - sendMessages("BrokerA", virtualTopic, 1); - - MessageIdList msgsA = getConsumerMessages("BrokerA", clientA); - MessageIdList msgsB = getConsumerMessages("BrokerB", clientB); - - msgsA.waitForMessagesToArrive(1); - msgsB.waitForMessagesToArrive(1); - - // ensure we don't get any more messages - Thread.sleep(2000); - - assertEquals(1, msgsA.getMessageCount()); - assertEquals(1, msgsB.getMessageCount()); - } - - private void bridgeAndConfigureBrokers(String local, String remote) throws Exception { - NetworkConnector bridge = bridgeBrokers(local, remote); - bridge.setDecreaseNetworkConsumerPriority(true); - } - - private void dontBridgeVirtualTopicConsumerQueues(String local, String remote) throws Exception { - NetworkConnector bridge = bridgeBrokers(local, remote); - bridge.setDecreaseNetworkConsumerPriority(true); - - LinkedList excludedDestinations = new LinkedList<>(); - excludedDestinations.add(new ActiveMQQueue("Consumer.*.VirtualTopic.>")); - - bridge.setExcludedDestinations(excludedDestinations); - - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - String options = new String("?useJmx=false&deleteAllMessagesOnStartup=true"); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61616)/BrokerA" + options)); - createAndConfigureBroker(new URI("broker:(tcp://localhost:61617)/BrokerB" + options)); - } - - private BrokerService createAndConfigureBroker(URI uri) throws Exception { - BrokerService broker = createBroker(uri); - configurePersistenceAdapter(broker); - return broker; - } - - protected void configurePersistenceAdapter(BrokerService broker) throws IOException { - File dataFileDir = new File("target/test-amq-data/kahadb/" + broker.getBrokerName()); - KahaDBStore kaha = new KahaDBStore(); - kaha.setDirectory(dataFileDir); - broker.setPersistenceAdapter(kaha); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoMulticastDiscoveryBrokerTopicSendReceiveTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoMulticastDiscoveryBrokerTopicSendReceiveTest.java deleted file mode 100644 index 3639168756..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoMulticastDiscoveryBrokerTopicSendReceiveTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.JMSException; - -import org.apache.activemq.ActiveMQConnectionFactory; - -/** - * reproduced: https://issues.apache.org/jira/browse/AMQ-4107 - */ -public class TwoMulticastDiscoveryBrokerTopicSendReceiveTest extends TwoBrokerTopicSendReceiveTest { - - @Override - protected ActiveMQConnectionFactory createReceiverConnectionFactory() throws JMSException { - return createConnectionFactory("org/apache/activemq/usecases/receiver-discovery.xml", "receiver", "vm://receiver"); - } - - @Override - protected ActiveMQConnectionFactory createSenderConnectionFactory() throws JMSException { - return createConnectionFactory("org/apache/activemq/usecases/sender-discovery.xml", "sender", "vm://sender"); - } - - @Override - protected void setUp() throws Exception { - System.setProperty("groupId", getClass().getName() + "-" + System.currentTimeMillis()); - messageCount = 100000; - super.setUp(); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoSecureBrokerRequestReplyTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoSecureBrokerRequestReplyTest.java deleted file mode 100644 index 9684ae329c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/TwoSecureBrokerRequestReplyTest.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.activemq.usecases; - -import javax.jms.ConnectionFactory; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TemporaryQueue; - -import org.apache.activemq.ActiveMQConnection; -import org.apache.activemq.ActiveMQMessageConsumer; -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.command.ActiveMQQueue; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.ClassPathResource; - -public class TwoSecureBrokerRequestReplyTest extends JmsMultipleBrokersTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(TwoSecureBrokerRequestReplyTest.class); - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - - createBroker(new ClassPathResource("org/apache/activemq/usecases/sender-secured.xml")); - createBroker(new ClassPathResource("org/apache/activemq/usecases/receiver-secured.xml")); - } - - public void testRequestReply() throws Exception { - ActiveMQQueue requestReplyDest = new ActiveMQQueue("RequestReply"); - - startAllBrokers(); - waitForBridgeFormation(); - waitForMinTopicRegionConsumerCount("sender", 1); - waitForMinTopicRegionConsumerCount("receiver", 1); - - ConnectionFactory factory = getConnectionFactory("sender"); - ActiveMQConnection conn = (ActiveMQConnection) factory.createConnection("system", "manager"); - conn.setWatchTopicAdvisories(false); - conn.start(); - Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - - ConnectionFactory replyFactory = getConnectionFactory("receiver"); - for (int i = 0; i < 2000; i++) { - TemporaryQueue tempDest = session.createTemporaryQueue(); - MessageProducer producer = session.createProducer(requestReplyDest); - javax.jms.Message message = session.createTextMessage("req-" + i); - message.setJMSReplyTo(tempDest); - - ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session.createConsumer(tempDest); - producer.send(message); - - ActiveMQConnection replyConnection = (ActiveMQConnection) replyFactory.createConnection("system", "manager"); - replyConnection.setWatchTopicAdvisories(false); - replyConnection.start(); - Session replySession = replyConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQMessageConsumer replyConsumer = (ActiveMQMessageConsumer) replySession.createConsumer(requestReplyDest); - javax.jms.Message msg = replyConsumer.receive(10000); - assertNotNull("request message not null: " + i, msg); - MessageProducer replyProducer = replySession.createProducer(msg.getJMSReplyTo()); - replyProducer.send(session.createTextMessage("reply-" + i)); - replyConnection.close(); - - javax.jms.Message reply = consumer.receive(10000); - assertNotNull("reply message : " + i + ", to: " + tempDest + ", by consumer:" + consumer.getConsumerId(), reply); - consumer.close(); - tempDest.delete(); - LOG.info("message #" + i + " processed"); - } - - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/UnlimitedEnqueueTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/UnlimitedEnqueueTest.java deleted file mode 100644 index 6168423807..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/UnlimitedEnqueueTest.java +++ /dev/null @@ -1,137 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.activemq.usecases; - -import javax.jms.BytesMessage; -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageProducer; -import javax.jms.ResourceAllocationException; -import javax.jms.Session; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.FilePendingQueueMessageStoragePolicy; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.util.Wait; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.junit.Assert.assertTrue; - -public class UnlimitedEnqueueTest { - - private static final Logger LOG = LoggerFactory.getLogger(UnlimitedEnqueueTest.class); - BrokerService brokerService = null; - final long numMessages = 5000; - final long numThreads = 10; - final int payLoadSize = 100 * 1024; - - @Test - public void testEnqueueIsOnlyLimitedByDisk() throws Exception { - ExecutorService executor = Executors.newCachedThreadPool(); - for (int i = 0; i < numThreads; i++) { - executor.execute(new Producer(numMessages / numThreads)); - } - - assertTrue("Temp Store is filling ", Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - LOG.info("Temp Usage, " + brokerService.getSystemUsage().getTempUsage() + ", full=" + brokerService.getSystemUsage().getTempUsage().isFull() + ", % usage: " + brokerService.getSystemUsage().getTempUsage().getPercentUsage()); - return brokerService.getSystemUsage().getTempUsage().getPercentUsage() > 1; - } - }, TimeUnit.MINUTES.toMillis(4))); - executor.shutdownNow(); - } - - @Before - public void createBrokerService() throws Exception { - brokerService = new BrokerService(); - brokerService.setDeleteAllMessagesOnStartup(true); - brokerService.setAdvisorySupport(false); - - // optional, reduce the usage limit so that spooling will occur faster - brokerService.getSystemUsage().getMemoryUsage().setLimit(10 * 1024 * 1024); - brokerService.getSystemUsage().getTempUsage().setLimit((numMessages * payLoadSize) + (1000 * payLoadSize)); - - PolicyMap policyMap = new PolicyMap(); - List entries = new ArrayList<>(); - PolicyEntry policy = new PolicyEntry(); - - // NB: ensure queue cursor limit is below the default 70% usage that the destination will use - // if they are the same, the queue memory limit and flow control will kick in first - policy.setCursorMemoryHighWaterMark(20); - - // on by default - //policy.setProducerFlowControl(true); - policy.setQueue(">"); - - // policy that will spool references to disk - policy.setPendingQueuePolicy(new FilePendingQueueMessageStoragePolicy()); - entries.add(policy); - policyMap.setPolicyEntries(entries); - brokerService.setDestinationPolicy(policyMap); - - brokerService.start(); - } - - public class Producer implements Runnable { - - private final long numberOfMessages; - - public Producer(final long n) { - this.numberOfMessages = n; - } - - @Override - public void run() { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerService.getVmConnectorURI()); - try { - Connection conn = factory.createConnection(); - conn.start(); - byte[] bytes = new byte[payLoadSize]; - for (int i = 0; i < numberOfMessages; i++) { - Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - Destination destination = session.createQueue("test-queue"); - MessageProducer producer = session.createProducer(destination); - producer.setDeliveryMode(DeliveryMode.PERSISTENT); - BytesMessage message = session.createBytesMessage(); - message.writeBytes(bytes); - try { - producer.send(message); - } catch (ResourceAllocationException e) { - e.printStackTrace(); - } - session.close(); - } - } catch (JMSException e) { - // expect interrupted exception on shutdownNow - } - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/VerifyNetworkConsumersDisconnectTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/VerifyNetworkConsumersDisconnectTest.java deleted file mode 100644 index 4db4b423ac..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/VerifyNetworkConsumersDisconnectTest.java +++ /dev/null @@ -1,273 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.usecases; - -import javax.jms.Destination; -import javax.jms.MessageConsumer; -import javax.management.ObjectName; -import java.lang.Thread.UncaughtExceptionHandler; -import java.net.URI; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.jmx.ManagementContext; -import org.apache.activemq.broker.jmx.QueueViewMBean; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.network.NetworkConnector; -import org.apache.activemq.util.Wait; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class VerifyNetworkConsumersDisconnectTest extends JmsMultipleBrokersTestSupport implements UncaughtExceptionHandler { - - public static final int BROKER_COUNT = 3; - public static final int CONSUMER_COUNT = 5; - public static final int MESSAGE_COUNT = 0; - public static final boolean DUPLEX = false; - public static final boolean CONDUIT = true; - - public static final int NETWORK_TTL = 6; - private static final Logger LOG = LoggerFactory.getLogger(VerifyNetworkConsumersDisconnectTest.class); - public static final int TIMEOUT = 30000; - - protected Map consumerMap; - final Map unhandledExceptions = new HashMap<>(); - - private void assertNoUnhandledExceptions() { - for (Entry e : unhandledExceptions.entrySet()) { - LOG.error("Thread:" + e.getKey() + " Had unexpected: " + e.getValue()); - } - assertTrue("There are no unhandled exceptions, see: log for detail on: " + unhandledExceptions, unhandledExceptions.isEmpty()); - } - - public NetworkConnector bridge(String from, String to) throws Exception { - NetworkConnector networkConnector = bridgeBrokers(from, to, true, NETWORK_TTL, CONDUIT); - networkConnector.setSuppressDuplicateQueueSubscriptions(true); - networkConnector.setDecreaseNetworkConsumerPriority(true); - networkConnector.setDuplex(DUPLEX); - return networkConnector; - } - - /*why conduit proxy proxy consumers gets us in a knot w.r.t removal - DC-7 for CA-9, add DB-15, remove CA-9, add CB-8 - CB-8 add DC-7 - CB-8 - why not dead? - CB-8 for BA-6, add BD-15, remove BA-6 - BD-15 for DA-11, add DC-7 - */ - public void testConsumerOnEachBroker() throws Exception { - bridge("Broker0", "Broker1"); - if (!DUPLEX) - bridge("Broker1", "Broker0"); - - bridge("Broker1", "Broker2"); - if (!DUPLEX) - bridge("Broker2", "Broker1"); - - startAllBrokers(); - waitForBridgeFormation(brokers.get("Broker0").broker, 1, 0); - waitForBridgeFormation(brokers.get("Broker2").broker, 1, 0); - waitForBridgeFormation(brokers.get("Broker1").broker, 1, 0); - waitForBridgeFormation(brokers.get("Broker1").broker, 1, 1); - - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - for (int i = 0; i < BROKER_COUNT; i++) { - consumerMap.put("Consumer:" + i + ":0", createConsumer("Broker" + i, dest)); - } - - assertExactConsumersConnect("Broker0", 3, 1, TIMEOUT); - assertExactConsumersConnect("Broker2", 3, 1, TIMEOUT); - // piggy in the middle - assertExactConsumersConnect("Broker1", 3, 1, TIMEOUT); - - assertNoUnhandledExceptions(); - - LOG.info("Complete the mesh - 0->2"); - - // shorter route - NetworkConnector nc = bridge("Broker0", "Broker2"); - nc.setBrokerName("Broker0"); - nc.start(); - - if (!DUPLEX) { - LOG.info("... complete the mesh - 2->0"); - nc = bridge("Broker2", "Broker0"); - nc.setBrokerName("Broker2"); - nc.start(); - } - - // wait for consumers to get propagated - for (int i = 0; i < BROKER_COUNT; i++) { - assertExactConsumersConnect("Broker" + i, 3, 1, TIMEOUT); - } - - // reverse order close - consumerMap.get("Consumer:" + 2 + ":0").close(); - TimeUnit.SECONDS.sleep(1); - consumerMap.get("Consumer:" + 1 + ":0").close(); - TimeUnit.SECONDS.sleep(1); - consumerMap.get("Consumer:" + 0 + ":0").close(); - - LOG.info("Check for no consumers.."); - for (int i = 0; i < BROKER_COUNT; i++) { - assertExactConsumersConnect("Broker" + i, 0, 0, TIMEOUT); - } - - } - - public void testXConsumerOnEachBroker() throws Exception { - bridge("Broker0", "Broker1"); - if (!DUPLEX) - bridge("Broker1", "Broker0"); - - bridge("Broker1", "Broker2"); - if (!DUPLEX) - bridge("Broker2", "Broker1"); - - startAllBrokers(); - - waitForBridgeFormation(brokers.get("Broker0").broker, 1, 0); - waitForBridgeFormation(brokers.get("Broker2").broker, 1, 0); - waitForBridgeFormation(brokers.get("Broker1").broker, 1, 0); - waitForBridgeFormation(brokers.get("Broker1").broker, 1, 1); - - Destination dest = createDestination("TEST.FOO", false); - - // Setup consumers - for (int i = 0; i < BROKER_COUNT; i++) { - for (int j = 0; j < CONSUMER_COUNT; j++) - consumerMap.put("Consumer:" + i + ":" + j, createConsumer("Broker" + i, dest)); - } - - for (int i = 0; i < BROKER_COUNT; i++) { - assertExactConsumersConnect("Broker" + i, CONSUMER_COUNT + (BROKER_COUNT - 1), 1, TIMEOUT); - } - - assertNoUnhandledExceptions(); - - LOG.info("Complete the mesh - 0->2"); - - // shorter route - NetworkConnector nc = bridge("Broker0", "Broker2"); - nc.setBrokerName("Broker0"); - nc.start(); - - waitForBridgeFormation(brokers.get("Broker0").broker, 1, 1); - - if (!DUPLEX) { - LOG.info("... complete the mesh - 2->0"); - nc = bridge("Broker2", "Broker0"); - nc.setBrokerName("Broker2"); - nc.start(); - } - - waitForBridgeFormation(brokers.get("Broker2").broker, 1, 1); - - for (int i = 0; i < BROKER_COUNT; i++) { - assertExactConsumersConnect("Broker" + i, CONSUMER_COUNT + (BROKER_COUNT - 1), 1, TIMEOUT); - } - - // reverse order close - for (int i = 0; i < CONSUMER_COUNT; i++) { - consumerMap.get("Consumer:" + 2 + ":" + i).close(); - TimeUnit.SECONDS.sleep(1); - consumerMap.get("Consumer:" + 1 + ":" + i).close(); - TimeUnit.SECONDS.sleep(1); - consumerMap.get("Consumer:" + 0 + ":" + i).close(); - } - - LOG.info("Check for no consumers.."); - for (int i = 0; i < BROKER_COUNT; i++) { - assertExactConsumersConnect("Broker" + i, 0, 0, TIMEOUT); - } - - } - - protected void assertExactConsumersConnect(final String brokerName, - final int count, - final int numChecks, - long timeout) throws Exception { - final ManagementContext context = brokers.get(brokerName).broker.getManagementContext(); - final AtomicInteger stability = new AtomicInteger(0); - assertTrue("Expected consumers count: " + count + " on: " + brokerName, Wait.waitFor(new Wait.Condition() { - @Override - public boolean isSatisified() throws Exception { - try { - QueueViewMBean queueViewMBean = (QueueViewMBean) context.newProxyInstance(brokers.get(brokerName).broker.getAdminView().getQueues()[0], QueueViewMBean.class, false); - long currentCount = queueViewMBean.getConsumerCount(); - LOG.info("On " + brokerName + " current consumer count for " + queueViewMBean + ", " + currentCount); - LinkedList consumerIds = new LinkedList<>(); - for (ObjectName objectName : queueViewMBean.getSubscriptions()) { - consumerIds.add(objectName.getKeyProperty("consumerId")); - } - LOG.info("Sub IDs: " + consumerIds); - if (currentCount == count) { - stability.incrementAndGet(); - } else { - stability.set(0); - } - return stability.get() > numChecks; - } catch (Exception e) { - LOG.warn(": ", e); - return false; - } - } - }, timeout)); - } - - @Override - public void setUp() throws Exception { - super.setAutoFail(true); - super.setUp(); - - unhandledExceptions.clear(); - Thread.setDefaultUncaughtExceptionHandler(this); - - // Setup n brokers - for (int i = 0; i < BROKER_COUNT; i++) { - createBroker(new URI("broker:(tcp://localhost:6161" + i + ")/Broker" + i + "?persistent=false&useJmx=true&brokerId=Broker" + i)); - } - - consumerMap = new LinkedHashMap<>(); - } - - @Override - protected void configureBroker(BrokerService brokerService) { - PolicyEntry policyEntry = new PolicyEntry(); - policyEntry.setExpireMessagesPeriod(0); - PolicyMap policyMap = new PolicyMap(); - policyMap.setDefaultEntry(policyEntry); - brokerService.setDestinationPolicy(policyMap); - } - - @Override - public void uncaughtException(Thread t, Throwable e) { - synchronized (unhandledExceptions) { - unhandledExceptions.put(t, e); - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/VirtualTopicNetworkClusterReactivationTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/VirtualTopicNetworkClusterReactivationTest.java deleted file mode 100644 index e44d113400..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/VirtualTopicNetworkClusterReactivationTest.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.activemq.usecases; - -import javax.jms.Connection; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.net.URI; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.JmsMultipleBrokersTestSupport; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.network.ConditionalNetworkBridgeFilterFactory; - -/** - * @author Christian Posta - */ -public class VirtualTopicNetworkClusterReactivationTest extends JmsMultipleBrokersTestSupport { - - private static final String BROKER_A = "brokerA"; - private static final String BROKER_B = "brokerB"; - private static final String BROKER_A_TRANSPORT_URL = "tcp://localhost:61616"; - private static final String BROKER_B_TRANSPORT_URL = "tcp://localhost:61617"; - private static final long DEFAULT_SLEEP_MS = 1000; - - private ActiveMQTopic topic = new ActiveMQTopic("VirtualTopic.FOO.TEST"); - private ActiveMQQueue queue = new ActiveMQQueue("Consumer.FOO.VirtualTopic.FOO.TEST"); - - /** - * This test shows how to use pub/sub to mimic durable subscribers in a network of brokers. - * - * When using durable subscribers in a broker cluster, you can encounter a situation where a - * subscription gets orphaned on a broker when the client disconnects and reattaches to another - * broker in the cluster. Since the clientID/durableName only need to be unique within a single - * broker, it's possible to have a durable sub on multiple brokers in a cluster. - * - * FOR EXAMPLE: - * Broker A and B are networked together in both directions to form a full mesh. If durable - * subscriber 'foo' subscribes to failover(A,B) and ends up on B, and a producer on A, messages - * will be demand forwarded from A to B. But if the durable sub 'foo' disconnects from B, - * then reconnects to failover(A,B) but this time gets connected to A, the subscription on - * B will still be there are continue to receive messages (and possibly have missed messages - * sent there while gone) - * - * We can avoid all of this mess with virtual topics as seen below: - * - * @throws JMSException - */ - public void testDurableSubReconnectFromAtoB() throws JMSException { - // create consumer on broker B - ActiveMQConnectionFactory bConnFactory = new ActiveMQConnectionFactory(BROKER_B_TRANSPORT_URL + "?jms.prefetchPolicy.queuePrefetch=0"); - Connection bConn = bConnFactory.createConnection(); - bConn.start(); - Session bSession = bConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer bSessionConsumer = bSession.createConsumer(queue); - - // create producer on A - ActiveMQConnectionFactory aConnFactory = new ActiveMQConnectionFactory(BROKER_A_TRANSPORT_URL); - Connection aProducerConn = aConnFactory.createConnection(); - aProducerConn.start(); - - Session aProducerSession = aProducerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = aProducerSession.createProducer(topic); - produce(producer, aProducerSession, 5); - - // sleep for a sec to let the messages get bridged over to broker B - sleep(); - - // consumer on B has not consumed any messages, and for some reason goes away: - bSessionConsumer.close(); - bSession.close(); - bConn.close(); - - // let the bridge catch up - sleep(); - - // and now consumer reattaches to A and wants the messages that were sent to B - Connection aConsumerConn = aConnFactory.createConnection(); - aConsumerConn.start(); - Session aConsumerSession = aConsumerConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageConsumer aSessionConsumer = aConsumerSession.createConsumer(queue); - - sleep(); - - // they should all be there - consume(aSessionConsumer, 5); - - } - - private void consume(MessageConsumer durable, int numMessagesExpected) throws JMSException { - for (int i = 0; i < numMessagesExpected; i++) { - Message message = durable.receive(1000); - assertNotNull(message); - TextMessage textMessage = (TextMessage) message; - System.out.println("received: " + textMessage.getText()); - assertEquals("message: " + i, textMessage.getText()); - } - } - - private void produce(MessageProducer producer, Session sess, int numMessages) throws JMSException { - for (int i = 0; i < numMessages; i++) { - producer.send(sess.createTextMessage("message: " + i)); - } - } - - @Override - protected void setUp() throws Exception { - maxSetupTime = 1000; - super.setAutoFail(true); - super.setUp(); - final String options = "?persistent=true&useJmx=false&deleteAllMessagesOnStartup=true"; - - BrokerService brokerServiceA = createBroker(new URI(String.format("broker:(%s)/%s%s", BROKER_A_TRANSPORT_URL, BROKER_A, options))); - brokerServiceA.setDestinationPolicy(buildPolicyMap()); - brokerServiceA.setDestinations(new ActiveMQDestination[]{queue}); - - BrokerService brokerServiceB = createBroker(new URI(String.format("broker:(%s)/%s%s", BROKER_B_TRANSPORT_URL, BROKER_B, options))); - brokerServiceB.setDestinationPolicy(buildPolicyMap()); - brokerServiceB.setDestinations(new ActiveMQDestination[]{queue}); - - // bridge brokers to each other statically (static: discovery) - bridgeBrokers(BROKER_A, BROKER_B); - bridgeBrokers(BROKER_B, BROKER_A); - - startAllBrokers(); - } - - private PolicyMap buildPolicyMap() { - PolicyMap policyMap = new PolicyMap(); - PolicyEntry policyEntry = new PolicyEntry(); - policyEntry.setOptimizedDispatch(true); - ConditionalNetworkBridgeFilterFactory networkBridgeFilterFactory = new ConditionalNetworkBridgeFilterFactory(); - networkBridgeFilterFactory.setReplayWhenNoConsumers(true); - policyEntry.setNetworkBridgeFilterFactory(networkBridgeFilterFactory); - policyEntry.setEnableAudit(false); - policyMap.put(new ActiveMQQueue("Consumer.*.VirtualTopic.>"), policyEntry); - return policyMap; - } - - private void sleep() { - try { - Thread.sleep(DEFAULT_SLEEP_MS); - } catch (InterruptedException igonred) { - } - } - - private void sleep(int milliSecondTime) { - try { - Thread.sleep(milliSecondTime); - } catch (InterruptedException igonred) { - } - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/activemq.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/activemq.xml deleted file mode 100644 index 908b0cf2ee..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/activemq.xml +++ /dev/null @@ -1,108 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker1.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker1.xml deleted file mode 100644 index 8a27d497dd..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker1.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker1A.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker1A.xml deleted file mode 100644 index 1d0c34e98d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker1A.xml +++ /dev/null @@ -1,193 +0,0 @@ - - - - - - - - classpath:activemq-browse.properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker1B.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker1B.xml deleted file mode 100644 index 639b53d190..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker1B.xml +++ /dev/null @@ -1,194 +0,0 @@ - - - - - - - - - classpath:activemq-browse.properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker2.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker2.xml deleted file mode 100644 index 0b34f0e4e6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker2.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker2A.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker2A.xml deleted file mode 100644 index 0e2008cf61..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker2A.xml +++ /dev/null @@ -1,193 +0,0 @@ - - - - - - - - classpath:activemq-browse.properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker2B.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker2B.xml deleted file mode 100644 index 2139cfb2d8..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker2B.xml +++ /dev/null @@ -1,195 +0,0 @@ - - - - - - - - classpath:activemq-browse.properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker3A.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker3A.xml deleted file mode 100644 index f879b1d679..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker3A.xml +++ /dev/null @@ -1,192 +0,0 @@ - - - - - - - - classpath:activemq-browse.properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker3B.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker3B.xml deleted file mode 100644 index 5301677145..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/browse-broker3B.xml +++ /dev/null @@ -1,191 +0,0 @@ - - - - - - - - classpath:activemq-browse.properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/multicast-broker-1.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/multicast-broker-1.xml deleted file mode 100644 index a3123b6f33..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/multicast-broker-1.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/multicast-broker-2.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/multicast-broker-2.xml deleted file mode 100644 index 48cc372afb..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/multicast-broker-2.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/multicast-broker-auto.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/multicast-broker-auto.xml deleted file mode 100644 index 7c298d8c11..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/multicast-broker-auto.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rebalance-broker1.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rebalance-broker1.xml deleted file mode 100644 index 0ed33d7bdd..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rebalance-broker1.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rebalance-broker2.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rebalance-broker2.xml deleted file mode 100644 index fd96b883bf..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rebalance-broker2.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rebalance-broker3.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rebalance-broker3.xml deleted file mode 100644 index 3438feec17..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rebalance-broker3.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-activecluster.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-activecluster.xml deleted file mode 100644 index 719e6d2cef..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-activecluster.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-discovery.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-discovery.xml deleted file mode 100644 index 9ad519d674..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-discovery.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-duplex.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-duplex.xml deleted file mode 100644 index 9b4750fd69..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-duplex.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-http.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-http.xml deleted file mode 100644 index 06aba93e2f..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-http.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-secured.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-secured.xml deleted file mode 100644 index 33b5a2ee1a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-secured.xml +++ /dev/null @@ -1,78 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-zeroconf.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-zeroconf.xml deleted file mode 100644 index 470fe35e24..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver-zeroconf.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver.xml deleted file mode 100644 index 50d2db2751..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/receiver.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/replication-broker1.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/replication-broker1.xml deleted file mode 100644 index 20a974cc69..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/replication-broker1.xml +++ /dev/null @@ -1,121 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/replication-broker2.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/replication-broker2.xml deleted file mode 100644 index 700095e713..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/replication-broker2.xml +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/replication-broker3.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/replication-broker3.xml deleted file mode 100644 index f3ee99ded0..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/replication-broker3.xml +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/replication-broker4.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/replication-broker4.xml deleted file mode 100644 index 96b778ab7d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/replication-broker4.xml +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rerouting-activemq-A.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rerouting-activemq-A.xml deleted file mode 100644 index bc367f7a02..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rerouting-activemq-A.xml +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rerouting-activemq-B.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rerouting-activemq-B.xml deleted file mode 100644 index 524a338fc4..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rerouting-activemq-B.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rerouting-activemq-C.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rerouting-activemq-C.xml deleted file mode 100644 index 8c5c810385..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rerouting-activemq-C.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rerouting-activemq-D.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rerouting-activemq-D.xml deleted file mode 100644 index 8a2de52bfe..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/rerouting-activemq-D.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-activecluster.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-activecluster.xml deleted file mode 100644 index 38f7a3cb27..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-activecluster.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-discovery.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-discovery.xml deleted file mode 100644 index 5319b39dd9..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-discovery.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-duplex.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-duplex.xml deleted file mode 100644 index a8195c0745..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-duplex.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-http.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-http.xml deleted file mode 100644 index b5f5cea508..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-http.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-secured.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-secured.xml deleted file mode 100644 index 0eb9562d33..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-secured.xml +++ /dev/null @@ -1,82 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-zeroconf.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-zeroconf.xml deleted file mode 100644 index aa695566af..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender-zeroconf.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender.xml deleted file mode 100644 index c83d89b63c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/usecases/sender.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/LinkedNodeTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/LinkedNodeTest.java deleted file mode 100644 index b0ab40a68a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/LinkedNodeTest.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.activemq.util; - -import junit.framework.TestCase; - -/** - * @author chirino - */ -public class LinkedNodeTest extends TestCase { - - static class IntLinkedNode extends LinkedNode { - - public final int v; - - public IntLinkedNode(int v) { - this.v = v; - } - - @Override - public String toString() { - return "" + v; - } - } - - IntLinkedNode i1 = new IntLinkedNode(1); - IntLinkedNode i2 = new IntLinkedNode(2); - IntLinkedNode i3 = new IntLinkedNode(3); - IntLinkedNode i4 = new IntLinkedNode(4); - IntLinkedNode i5 = new IntLinkedNode(5); - IntLinkedNode i6 = new IntLinkedNode(6); - - public void testLinkAfter() { - - i1.linkAfter(i2.linkAfter(i3)); - // Order should be 1,2,3 - - assertTrue(i1.getNext() == i2); - assertTrue(i1.getNext().getNext() == i3); - assertNull(i1.getNext().getNext().getNext()); - - assertTrue(i3.getPrevious() == i2); - assertTrue(i3.getPrevious().getPrevious() == i1); - assertNull(i3.getPrevious().getPrevious().getPrevious()); - - assertTrue(i1.isHeadNode()); - assertFalse(i1.isTailNode()); - assertFalse(i2.isHeadNode()); - assertFalse(i2.isTailNode()); - assertTrue(i3.isTailNode()); - assertFalse(i3.isHeadNode()); - - i1.linkAfter(i4.linkAfter(i5)); - - // Order should be 1,4,5,2,3 - - assertTrue(i1.getNext() == i4); - assertTrue(i1.getNext().getNext() == i5); - assertTrue(i1.getNext().getNext().getNext() == i2); - assertTrue(i1.getNext().getNext().getNext().getNext() == i3); - assertNull(i1.getNext().getNext().getNext().getNext().getNext()); - - assertTrue(i3.getPrevious() == i2); - assertTrue(i3.getPrevious().getPrevious() == i5); - assertTrue(i3.getPrevious().getPrevious().getPrevious() == i4); - assertTrue(i3.getPrevious().getPrevious().getPrevious().getPrevious() == i1); - assertNull(i3.getPrevious().getPrevious().getPrevious().getPrevious().getPrevious()); - - assertTrue(i1.isHeadNode()); - assertFalse(i1.isTailNode()); - assertFalse(i4.isHeadNode()); - assertFalse(i4.isTailNode()); - assertFalse(i5.isHeadNode()); - assertFalse(i5.isTailNode()); - assertFalse(i2.isHeadNode()); - assertFalse(i2.isTailNode()); - assertTrue(i3.isTailNode()); - assertFalse(i3.isHeadNode()); - - } - - public void testLinkBefore() { - - i3.linkBefore(i2.linkBefore(i1)); - - assertTrue(i1.getNext() == i2); - assertTrue(i1.getNext().getNext() == i3); - assertNull(i1.getNext().getNext().getNext()); - - assertTrue(i3.getPrevious() == i2); - assertTrue(i3.getPrevious().getPrevious() == i1); - assertNull(i3.getPrevious().getPrevious().getPrevious()); - - assertTrue(i1.isHeadNode()); - assertFalse(i1.isTailNode()); - assertFalse(i2.isHeadNode()); - assertFalse(i2.isTailNode()); - assertTrue(i3.isTailNode()); - assertFalse(i3.isHeadNode()); - - i2.linkBefore(i5.linkBefore(i4)); - - // Order should be 1,4,5,2,3 - - assertTrue(i1.getNext() == i4); - assertTrue(i1.getNext().getNext() == i5); - assertTrue(i1.getNext().getNext().getNext() == i2); - assertTrue(i1.getNext().getNext().getNext().getNext() == i3); - assertNull(i1.getNext().getNext().getNext().getNext().getNext()); - - assertTrue(i3.getPrevious() == i2); - assertTrue(i3.getPrevious().getPrevious() == i5); - assertTrue(i3.getPrevious().getPrevious().getPrevious() == i4); - assertTrue(i3.getPrevious().getPrevious().getPrevious().getPrevious() == i1); - assertNull(i3.getPrevious().getPrevious().getPrevious().getPrevious().getPrevious()); - - assertTrue(i1.isHeadNode()); - assertFalse(i1.isTailNode()); - assertFalse(i4.isHeadNode()); - assertFalse(i4.isTailNode()); - assertFalse(i5.isHeadNode()); - assertFalse(i5.isTailNode()); - assertFalse(i2.isHeadNode()); - assertFalse(i2.isTailNode()); - assertTrue(i3.isTailNode()); - assertFalse(i3.isHeadNode()); - - } - - public void testUnlink() { - - i1.linkAfter(i2.linkAfter(i3)); - i3.linkAfter(i4); - i1.linkBefore(i5); - i1.linkAfter(i6); - - // Order should be 5,1,6,2,3,4 - i4.unlink(); - i5.unlink(); - i6.unlink(); - - // Order should be 1,2,3 - - assertTrue(i1.getNext() == i2); - assertTrue(i1.getNext().getNext() == i3); - assertNull(i1.getNext().getNext().getNext()); - - assertTrue(i3.getPrevious() == i2); - assertTrue(i3.getPrevious().getPrevious() == i1); - assertNull(i3.getPrevious().getPrevious().getPrevious()); - - assertTrue(i1.isHeadNode()); - assertFalse(i1.isTailNode()); - assertFalse(i2.isHeadNode()); - assertFalse(i2.isTailNode()); - assertTrue(i3.isTailNode()); - assertFalse(i3.isHeadNode()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/LockFileTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/LockFileTest.java deleted file mode 100644 index 4fdbb0e4fa..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/LockFileTest.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.activemq.util; - -import java.io.File; - -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class LockFileTest { - - @Test - public void testNoDeleteOnUnlockIfNotLocked() throws Exception { - - File lockFile = new File(IOHelper.getDefaultDataDirectory(), "lockToTest1"); - IOHelper.mkdirs(lockFile.getParentFile()); - lockFile.createNewFile(); - - LockFile underTest = new LockFile(lockFile, true); - - underTest.lock(); - - lockFile.delete(); - - assertFalse("no longer valid", underTest.keepAlive()); - - // a slave gets in - lockFile.createNewFile(); - - underTest.unlock(); - - assertTrue("file still exists after unlock when not locked", lockFile.exists()); - - } - - @Test - public void testDeleteOnUnlockIfLocked() throws Exception { - - File lockFile = new File(IOHelper.getDefaultDataDirectory(), "lockToTest2"); - IOHelper.mkdirs(lockFile.getParentFile()); - lockFile.createNewFile(); - - LockFile underTest = new LockFile(lockFile, true); - - underTest.lock(); - - assertTrue("valid", underTest.keepAlive()); - - underTest.unlock(); - - assertFalse("file deleted on unlock", lockFile.exists()); - - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/ReflectionSupportTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/ReflectionSupportTest.java deleted file mode 100644 index 4bb488822d..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/ReflectionSupportTest.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.activemq.util; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Properties; - -import junit.framework.TestCase; - -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; - -public class ReflectionSupportTest extends TestCase { - - List favorites = new ArrayList<>(); - String favoritesString = "[queue://test, topic://test]"; - List nonFavorites = new ArrayList<>(); - String nonFavoritesString = "[topic://test1]"; - - @Override - public void setUp() { - favorites.add(new ActiveMQQueue("test")); - favorites.add(new ActiveMQTopic("test")); - nonFavorites.add(new ActiveMQTopic("test1")); - } - - public void testSetProperties() throws URISyntaxException { - SimplePojo pojo = new SimplePojo(); - HashMap map = new HashMap<>(); - map.put("age", "27"); - map.put("name", "Hiram"); - map.put("enabled", "true"); - map.put("uri", "test://value"); - map.put("favorites", favoritesString); - map.put("nonFavorites", nonFavoritesString); - map.put("others", null); - map.put("systems", "windows,mac"); - - IntrospectionSupport.setProperties(pojo, map); - - assertEquals(27, pojo.getAge()); - assertEquals("Hiram", pojo.getName()); - assertEquals(true, pojo.isEnabled()); - assertEquals(new URI("test://value"), pojo.getUri()); - assertEquals(favorites, pojo.getFavorites()); - assertEquals(nonFavorites, pojo.getNonFavorites()); - assertNull(pojo.getOthers()); - assertEquals("windows", pojo.getSystems()[0]); - assertEquals("mac", pojo.getSystems()[1]); - } - - public void testGetProperties() { - SimplePojo pojo = new SimplePojo(); - pojo.setAge(31); - pojo.setName("Dejan"); - pojo.setEnabled(true); - pojo.setFavorites(favorites); - pojo.setNonFavorites(nonFavorites); - pojo.setOthers(null); - pojo.setSystems(new String[]{"windows", "mac"}); - - Properties props = new Properties(); - - IntrospectionSupport.getProperties(pojo, props, null); - - assertEquals("Dejan", props.get("name")); - assertEquals("31", props.get("age")); - assertEquals("true", props.get("enabled")); - assertEquals(favoritesString, props.get("favorites")); - assertEquals(nonFavoritesString, props.get("nonFavorites")); - assertNull(props.get("others")); - assertEquals("windows,mac", props.get("systems")); - } - - public void testSetBoolean() { - - TestWitBoolean target = new TestWitBoolean(); - assertTrue(!target.getKeepAlive()); - - IntrospectionSupport.setProperty(target, "keepAlive", "TRUE"); - assertTrue(target.getKeepAlive()); - - IntrospectionSupport.setProperty(target, "keepAlive", "false"); - assertTrue(!target.getKeepAlive()); - } - - public static class TestWitBoolean { - - private Boolean keepAlive = Boolean.valueOf(false); - - public Boolean getKeepAlive() { - return keepAlive; - } - - public void setKeepAlive(Boolean keepAlive) { - this.keepAlive = keepAlive; - } - } -} - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/plugin-broker.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/plugin-broker.xml deleted file mode 100644 index 598ba926b1..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/util/plugin-broker.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/ConnectorXBeanConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/ConnectorXBeanConfigTest.java deleted file mode 100644 index c1bf9e0146..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/ConnectorXBeanConfigTest.java +++ /dev/null @@ -1,216 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.xbean; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; -import java.net.URI; -import java.util.List; -import java.util.concurrent.CountDownLatch; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.TransportConnector; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.network.NetworkConnector; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class ConnectorXBeanConfigTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(ConnectorXBeanConfigTest.class); - protected BrokerService brokerService; - - public void testConnectorConfiguredCorrectly() throws Exception { - - TransportConnector connector = brokerService.getTransportConnectors().get(0); - - assertEquals(new URI("tcp://localhost:61636"), connector.getUri()); - assertTrue(connector.getTaskRunnerFactory() == brokerService.getTaskRunnerFactory()); - - NetworkConnector netConnector = brokerService.getNetworkConnectors().get(0); - List excludedDestinations = netConnector.getExcludedDestinations(); - assertEquals(new ActiveMQQueue("exclude.test.foo"), excludedDestinations.get(0)); - assertEquals(new ActiveMQTopic("exclude.test.bar"), excludedDestinations.get(1)); - - List dynamicallyIncludedDestinations = netConnector.getDynamicallyIncludedDestinations(); - assertEquals(new ActiveMQQueue("include.test.foo"), dynamicallyIncludedDestinations.get(0)); - assertEquals(new ActiveMQTopic("include.test.bar"), dynamicallyIncludedDestinations.get(1)); - } - - public void testBrokerRestartIsAllowed() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - - // redundant start is now ignored - brokerService.start(); - } - - public void testForceBrokerRestart() throws Exception { - brokerService.stop(); - brokerService.waitUntilStopped(); - - brokerService.start(true); // force restart - brokerService.waitUntilStarted(); - - LOG.info("try and connect to restarted broker"); - //send and receive a message from a restarted broker - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61636"); - Connection conn = factory.createConnection(); - Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); - conn.start(); - Destination dest = new ActiveMQQueue("test"); - MessageConsumer consumer = sess.createConsumer(dest); - MessageProducer producer = sess.createProducer(dest); - producer.send(sess.createTextMessage("test")); - TextMessage msg = (TextMessage) consumer.receive(1000); - assertEquals("test", msg.getText()); - } - - public void testBrokerWontStop() throws Exception { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?async=false"); - factory.setDispatchAsync(false); - factory.setAlwaysSessionAsync(false); - Connection conn = factory.createConnection(); - final Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); - conn.start(); - final Destination dest = new ActiveMQQueue("TEST"); - final CountDownLatch stop = new CountDownLatch(1); - final CountDownLatch sendSecond = new CountDownLatch(1); - final CountDownLatch shutdown = new CountDownLatch(1); - final CountDownLatch test = new CountDownLatch(1); - - ActiveMQConnectionFactory testFactory = new ActiveMQConnectionFactory("vm://localhost?async=false"); - Connection testConn = testFactory.createConnection(); - testConn.start(); - Destination testDestination = sess.createQueue("NEW"); - Session testSess = testConn.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer testProducer = testSess.createProducer(testDestination); - - final Thread consumerThread = new Thread() { - @Override - public void run() { - try { - MessageProducer producer = sess.createProducer(dest); - producer.send(sess.createTextMessage("msg1")); - MessageConsumer consumer = sess.createConsumer(dest); - consumer.setMessageListener(new MessageListener() { - @Override - public void onMessage(Message message) { - try { - // send a message that will block - Thread.sleep(2000); - sendSecond.countDown(); - // try to stop the broker - Thread.sleep(5000); - stop.countDown(); - // run the test - Thread.sleep(5000); - test.countDown(); - shutdown.await(); - } catch (InterruptedException ie) { - } - } - }); - } catch (Exception e) { - e.printStackTrace(); - } - } - }; - - consumerThread.start(); - - final Thread producerThread = new Thread() { - @Override - public void run() { - try { - sendSecond.await(); - MessageProducer producer = sess.createProducer(dest); - producer.send(sess.createTextMessage("msg2")); - } catch (Exception e) { - e.printStackTrace(); - } - } - }; - - producerThread.start(); - - final Thread stopThread = new Thread() { - @Override - public void run() { - try { - stop.await(); - brokerService.stop(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }; - - stopThread.start(); - - test.await(); - try { - testSess.createConsumer(testDestination); - fail("Should have failed creating a consumer!"); - } catch (Exception e) { - e.printStackTrace(); - } - - try { - testProducer.send(testSess.createTextMessage("msg3")); - fail("Should have failed sending a message!"); - } catch (Exception e) { - e.printStackTrace(); - } - - shutdown.countDown(); - - } - - @Override - protected void setUp() throws Exception { - brokerService = createBroker(); - brokerService.start(); - } - - @Override - protected void tearDown() throws Exception { - if (brokerService != null) { - brokerService.stop(); - } - } - - protected BrokerService createBroker() throws Exception { - String uri = "org/apache/activemq/xbean/connector-test.xml"; - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/JDBCPersistenceAdapterXBeanConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/JDBCPersistenceAdapterXBeanConfigTest.java deleted file mode 100644 index e1b8d0eb21..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/JDBCPersistenceAdapterXBeanConfigTest.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.activemq.xbean; - -import java.net.URI; - -import junit.framework.TestCase; - -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.store.PersistenceAdapter; -import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; - -/** - * - */ -public class JDBCPersistenceAdapterXBeanConfigTest extends TestCase { - - protected BrokerService brokerService; - - public void testConfiguredCorrectly() throws Exception { - - PersistenceAdapter persistenceAdapter = brokerService.getPersistenceAdapter(); - assertNotNull(persistenceAdapter); - assertTrue(persistenceAdapter instanceof JDBCPersistenceAdapter); - - JDBCPersistenceAdapter jpa = (JDBCPersistenceAdapter) persistenceAdapter; - assertEquals("BROKER1.", jpa.getStatements().getTablePrefix()); - - } - - @Override - protected void setUp() throws Exception { - brokerService = createBroker(); - brokerService.start(); - } - - @Override - protected void tearDown() throws Exception { - if (brokerService != null) { - brokerService.stop(); - } - } - - protected BrokerService createBroker() throws Exception { - String uri = "org/apache/activemq/xbean/jdbc-persistence-adapter-test.xml"; - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/JDBCPersistenceXBeanConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/JDBCPersistenceXBeanConfigTest.java deleted file mode 100644 index db36fe4d74..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/JDBCPersistenceXBeanConfigTest.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.activemq.xbean; - -import java.net.URI; - -import junit.framework.TestCase; - -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.store.PersistenceAdapter; -import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter; - -/** - * - */ -public class JDBCPersistenceXBeanConfigTest extends TestCase { - - protected BrokerService brokerService; - - public void testConfiguredCorrectly() throws Exception { - - PersistenceAdapter persistenceAdapter = brokerService.getPersistenceAdapter(); - assertNotNull(persistenceAdapter); - assertTrue(persistenceAdapter instanceof JDBCPersistenceAdapter); - - JDBCPersistenceAdapter jpa = (JDBCPersistenceAdapter) persistenceAdapter; - assertEquals("BROKER1.", jpa.getStatements().getTablePrefix()); - - } - - @Override - protected void setUp() throws Exception { - brokerService = createBroker(); - brokerService.start(); - } - - @Override - protected void tearDown() throws Exception { - if (brokerService != null) { - brokerService.stop(); - } - } - - protected BrokerService createBroker() throws Exception { - String uri = "org/apache/activemq/xbean/jdbc-persistence-test.xml"; - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/ManagementContextXBeanConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/ManagementContextXBeanConfigTest.java deleted file mode 100644 index 7597ea3bfd..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/ManagementContextXBeanConfigTest.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.activemq.xbean; - -import javax.management.MBeanServerConnection; -import javax.management.MBeanServerInvocationHandler; -import javax.management.ObjectName; -import javax.management.remote.JMXConnector; -import javax.management.remote.JMXConnectorFactory; -import javax.management.remote.JMXServiceURL; -import java.net.URI; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Map; - -import junit.framework.TestCase; - -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.jmx.BrokerViewMBean; -import org.apache.activemq.util.JMXSupport; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class ManagementContextXBeanConfigTest extends TestCase { - - protected BrokerService brokerService; - private static final transient Logger LOG = LoggerFactory.getLogger(ManagementContextXBeanConfigTest.class); - - public void testManagementContextConfiguredCorrectly() throws Exception { - assertEquals(2011, brokerService.getManagementContext().getConnectorPort()); - assertEquals("test.domain", brokerService.getManagementContext().getJmxDomainName()); - // Make sure the broker is registered in the right jmx domain. - Hashtable map = new Hashtable<>(); - map.put("type", "Broker"); - map.put("brokerName", JMXSupport.encodeObjectNamePart("localhost")); - ObjectName on = new ObjectName("test.domain", map); - Object value = brokerService.getManagementContext().getAttribute(on, "TotalEnqueueCount"); - assertNotNull(value); - } - - public void testSuccessAuthentication() throws Exception { - JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:2011/jmxrmi"); - Map env = new HashMap<>(); - env.put(JMXConnector.CREDENTIALS, new String[]{"admin", "activemq"}); - JMXConnector connector = JMXConnectorFactory.connect(url, env); - assertAuthentication(connector); - } - - public void testFailAuthentication() throws Exception { - JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:2011/jmxrmi"); - try { - JMXConnector connector = JMXConnectorFactory.connect(url, null); - assertAuthentication(connector); - } catch (SecurityException e) { - return; - } - fail("Should have thrown an exception"); - } - - public void assertAuthentication(JMXConnector connector) throws Exception { - connector.connect(); - MBeanServerConnection connection = connector.getMBeanServerConnection(); - ObjectName name = new ObjectName("test.domain:type=Broker,brokerName=localhost"); - BrokerViewMBean mbean = MBeanServerInvocationHandler.newProxyInstance(connection, name, BrokerViewMBean.class, true); - LOG.info("Broker " + mbean.getBrokerId() + " - " + mbean.getBrokerName()); - } - - @Override - protected void setUp() throws Exception { - brokerService = createBroker(); - brokerService.start(); - } - - @Override - protected void tearDown() throws Exception { - if (brokerService != null) { - brokerService.stop(); - } - } - - protected BrokerService createBroker() throws Exception { - String uri = "org/apache/activemq/xbean/management-context-test.xml"; - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithEmbeddedBrokerAndPersistenceTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithEmbeddedBrokerAndPersistenceTest.java deleted file mode 100644 index b9c96e8417..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithEmbeddedBrokerAndPersistenceTest.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.activemq.xbean; - -/** - * - * - */ -public class MultipleTestsWithEmbeddedBrokerAndPersistenceTest extends MultipleTestsWithEmbeddedBrokerTest { - - @Override - protected boolean isPersistent() { - return true; - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithEmbeddedBrokerTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithEmbeddedBrokerTest.java deleted file mode 100644 index ac9b56b4ab..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithEmbeddedBrokerTest.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.activemq.xbean; - -import javax.jms.Connection; - -import org.apache.activemq.EmbeddedBrokerTestSupport; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class MultipleTestsWithEmbeddedBrokerTest extends EmbeddedBrokerTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(MultipleTestsWithEmbeddedBrokerTest.class); - - protected Connection connection; - - public void test1() throws Exception { - } - - public void test2() throws Exception { - } - - @Override - protected void setUp() throws Exception { - LOG.info("### starting up the test case: " + getName()); - - super.setUp(); - connection = connectionFactory.createConnection(); - connection.start(); - LOG.info("### started up the test case: " + getName()); - } - - @Override - protected void tearDown() throws Exception { - connection.close(); - - super.tearDown(); - - LOG.info("### closed down the test case: " + getName()); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithSpringFactoryBeanTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithSpringFactoryBeanTest.java deleted file mode 100644 index 15a97746f6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithSpringFactoryBeanTest.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.activemq.xbean; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; - -import junit.framework.TestCase; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.broker.BrokerService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.support.AbstractApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * @author Neil Clayton - */ -public class MultipleTestsWithSpringFactoryBeanTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(MultipleTestsWithSpringFactoryBeanTest.class); - - protected AbstractApplicationContext context; - protected BrokerService service; - private Connection connection; - - public void test1() throws Exception { - } - - public void test2() throws Exception { - } - - @Override - protected void setUp() throws Exception { - LOG.info("### starting up the test case: " + getName()); - - super.setUp(); - context = new ClassPathXmlApplicationContext("org/apache/activemq/xbean/spring2.xml"); - service = (BrokerService) context.getBean("broker"); - - // already started - service.start(); - - connection = createConnectionFactory().createConnection(); - connection.start(); - LOG.info("### started up the test case: " + getName()); - } - - @Override - protected void tearDown() throws Exception { - connection.close(); - - // stopped as part of the context - service.stop(); - context.close(); - super.tearDown(); - - LOG.info("### closed down the test case: " + getName()); - } - - protected ConnectionFactory createConnectionFactory() { - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(); - factory.setBrokerURL("vm://localhost"); - return factory; - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithSpringXBeanFactoryBeanTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithSpringXBeanFactoryBeanTest.java deleted file mode 100644 index 289e0dfca9..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithSpringXBeanFactoryBeanTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.xbean; - -import org.apache.activemq.broker.BrokerService; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * - */ -public class MultipleTestsWithSpringXBeanFactoryBeanTest extends MultipleTestsWithEmbeddedBrokerTest { - - private ClassPathXmlApplicationContext context; - - @Override - protected BrokerService createBroker() throws Exception { - context = new ClassPathXmlApplicationContext("org/apache/activemq/xbean/spring2.xml"); - return (BrokerService) context.getBean("broker"); - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - if (context != null) { - context.destroy(); - } - } - -} - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithXBeanFactoryBeanTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithXBeanFactoryBeanTest.java deleted file mode 100644 index a5cdd3e6fd..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/MultipleTestsWithXBeanFactoryBeanTest.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.activemq.xbean; - -import org.apache.activemq.broker.BrokerService; -import org.springframework.core.io.ClassPathResource; - -/** - * - */ -public class MultipleTestsWithXBeanFactoryBeanTest extends MultipleTestsWithEmbeddedBrokerTest { - - @Override - protected BrokerService createBroker() throws Exception { - BrokerFactoryBean factory = new BrokerFactoryBean(); - factory.setConfig(new ClassPathResource("org/apache/activemq/xbean/activemq2.xml")); - factory.afterPropertiesSet(); - return factory.getBroker(); - } - -} - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanConfigTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanConfigTest.java deleted file mode 100644 index 05069cb283..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanConfigTest.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.activemq.xbean; - -import java.net.URI; - -import junit.framework.TestCase; - -import org.apache.activemq.broker.Broker; -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; -import org.apache.activemq.broker.ConnectionContext; -import org.apache.activemq.broker.region.Topic; -import org.apache.activemq.broker.region.policy.DispatchPolicy; -import org.apache.activemq.broker.region.policy.LastImageSubscriptionRecoveryPolicy; -import org.apache.activemq.broker.region.policy.RetainedMessageSubscriptionRecoveryPolicy; -import org.apache.activemq.broker.region.policy.RoundRobinDispatchPolicy; -import org.apache.activemq.broker.region.policy.StrictOrderDispatchPolicy; -import org.apache.activemq.broker.region.policy.SubscriptionRecoveryPolicy; -import org.apache.activemq.broker.region.policy.TimedSubscriptionRecoveryPolicy; -import org.apache.activemq.command.ActiveMQTopic; -import org.apache.activemq.command.ConnectionId; -import org.apache.activemq.command.ConnectionInfo; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class XBeanConfigTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(XBeanConfigTest.class); - - protected BrokerService brokerService; - protected Broker broker; - protected ConnectionContext context; - protected ConnectionInfo info; - - public void testBrokerConfiguredCorrectly() throws Exception { - - // Validate the system properties are being evaluated in xbean. - assertEquals("testbroker", brokerService.getBrokerName()); - - Topic topic = (Topic) broker.addDestination(context, new ActiveMQTopic("FOO.BAR"), true); - DispatchPolicy dispatchPolicy = topic.getDispatchPolicy(); - assertTrue("dispatchPolicy should be RoundRobinDispatchPolicy: " + dispatchPolicy, dispatchPolicy instanceof RoundRobinDispatchPolicy); - - SubscriptionRecoveryPolicy subscriptionRecoveryPolicy = topic.getSubscriptionRecoveryPolicy(); - subscriptionRecoveryPolicy = ((RetainedMessageSubscriptionRecoveryPolicy) subscriptionRecoveryPolicy).getWrapped(); - - assertTrue("subscriptionRecoveryPolicy should be LastImageSubscriptionRecoveryPolicy: " + subscriptionRecoveryPolicy, subscriptionRecoveryPolicy instanceof LastImageSubscriptionRecoveryPolicy); - - LOG.info("destination: " + topic); - LOG.info("dispatchPolicy: " + dispatchPolicy); - LOG.info("subscriptionRecoveryPolicy: " + subscriptionRecoveryPolicy); - - topic = (Topic) broker.addDestination(context, new ActiveMQTopic("ORDERS.BOOKS"), true); - dispatchPolicy = topic.getDispatchPolicy(); - assertTrue("dispatchPolicy should be StrictOrderDispatchPolicy: " + dispatchPolicy, dispatchPolicy instanceof StrictOrderDispatchPolicy); - - subscriptionRecoveryPolicy = topic.getSubscriptionRecoveryPolicy(); - subscriptionRecoveryPolicy = ((RetainedMessageSubscriptionRecoveryPolicy) subscriptionRecoveryPolicy).getWrapped(); - assertTrue("subscriptionRecoveryPolicy should be TimedSubscriptionRecoveryPolicy: " + subscriptionRecoveryPolicy, subscriptionRecoveryPolicy instanceof TimedSubscriptionRecoveryPolicy); - TimedSubscriptionRecoveryPolicy timedSubscriptionPolicy = (TimedSubscriptionRecoveryPolicy) subscriptionRecoveryPolicy; - assertEquals("getRecoverDuration()", 60000, timedSubscriptionPolicy.getRecoverDuration()); - - LOG.info("destination: " + topic); - LOG.info("dispatchPolicy: " + dispatchPolicy); - LOG.info("subscriptionRecoveryPolicy: " + subscriptionRecoveryPolicy); - } - - @Override - protected void setUp() throws Exception { - System.setProperty("brokername", "testbroker"); - brokerService = createBroker(); - broker = brokerService.getBroker(); - - // started automatically - // brokerService.start(); - - context = new ConnectionContext(); - context.setBroker(broker); - info = new ConnectionInfo(); - info.setClientId("James"); - info.setUserName("James"); - info.setConnectionId(new ConnectionId("1234")); - - try { - broker.addConnection(context, info); - } catch (Throwable e) { - e.printStackTrace(); - fail(e.getMessage()); - } - - assertNotNull("No broker created!"); - } - - @Override - protected void tearDown() throws Exception { - if (brokerService != null) { - brokerService.stop(); - } - } - - protected BrokerService createBroker() throws Exception { - String uri = "org/apache/activemq/xbean/activemq-policy.xml"; - LOG.info("Loading broker configuration from the classpath with URI: " + uri); - return BrokerFactory.createBroker(new URI("xbean:" + uri)); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanStartFalseTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanStartFalseTest.java deleted file mode 100644 index cbad360404..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanStartFalseTest.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.activemq.xbean; - -import java.net.URI; - -import junit.framework.TestCase; - -import org.apache.activemq.broker.BrokerFactory; -import org.apache.activemq.broker.BrokerService; - -public class XBeanStartFalseTest extends TestCase { - - public void testStartFalse() throws Exception { - BrokerService broker = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/xbean/activemq2.xml")); - assertFalse("Broker is started", broker.isStarted()); - } - -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanXmlTest.java b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanXmlTest.java deleted file mode 100644 index e8d2a763a0..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/XBeanXmlTest.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.activemq.xbean; - -import org.apache.activemq.broker.SpringTest; - -public class XBeanXmlTest extends SpringTest { - - @Override - public void testSenderWithSpringXml() throws Exception { - assertSenderConfig("org/apache/activemq/xbean/spring.xml"); - } -} diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/activemq-policy.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/activemq-policy.xml deleted file mode 100644 index 1188734af4..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/activemq-policy.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/activemq.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/activemq.xml deleted file mode 100644 index 9884523485..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/activemq.xml +++ /dev/null @@ -1,65 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/activemq2.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/activemq2.xml deleted file mode 100644 index 78d19959f6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/activemq2.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/connector-test.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/connector-test.xml deleted file mode 100644 index 5fb64033d4..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/connector-test.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/jdbc-persistence-adapter-test.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/jdbc-persistence-adapter-test.xml deleted file mode 100644 index e5f4f2624a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/jdbc-persistence-adapter-test.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/jdbc-persistence-test.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/jdbc-persistence-test.xml deleted file mode 100644 index d00a8b980b..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/jdbc-persistence-test.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/management-context-test.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/management-context-test.xml deleted file mode 100644 index 98f8c0f521..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/management-context-test.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/spring.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/spring.xml deleted file mode 100644 index ef37855089..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/spring.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/spring2.xml b/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/spring2.xml deleted file mode 100644 index 395e24deee..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/org/apache/activemq/xbean/spring2.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/spring-embedded-xbean-bean-ref.xml b/tests/activemq5-unit-tests/src/test/java/spring-embedded-xbean-bean-ref.xml deleted file mode 100644 index b6daf725c6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/spring-embedded-xbean-bean-ref.xml +++ /dev/null @@ -1,101 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 10 - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/spring-embedded-xbean-local.xml b/tests/activemq5-unit-tests/src/test/java/spring-embedded-xbean-local.xml deleted file mode 100644 index 584faea2b6..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/spring-embedded-xbean-local.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 10 - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/spring-embedded-xbean-noversion.xml b/tests/activemq5-unit-tests/src/test/java/spring-embedded-xbean-noversion.xml deleted file mode 100644 index e21073c3a3..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/spring-embedded-xbean-noversion.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 10 - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/spring-embedded-xbean.xml b/tests/activemq5-unit-tests/src/test/java/spring-embedded-xbean.xml deleted file mode 100644 index e21073c3a3..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/spring-embedded-xbean.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 10 - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/spring-embedded.xml b/tests/activemq5-unit-tests/src/test/java/spring-embedded.xml deleted file mode 100644 index 39f09503ea..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/spring-embedded.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 10 - - - - - - - - - - - - - - - - - - org.apache.activemq.spring.Test.spring.embedded - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/spring-jndi.xml b/tests/activemq5-unit-tests/src/test/java/spring-jndi.xml deleted file mode 100644 index 4ad519b1d8..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/spring-jndi.xml +++ /dev/null @@ -1,119 +0,0 @@ - - - - - - - - - - - - org.apache.activemq.jndi.ActiveMQInitialContextFactory - - example.Spring.MyTopic - - - - - - - - - - - ConnectionFactory - - - - - - - - - - MyTopic - - - - - - true - - - - - - - - - - - - - - - - - - true - - - - - - - - - - - - - - - - - - - 10 - - - - - - - - - - - - - - - - - - example.Spring.MyTopic - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/spring-queue.xml b/tests/activemq5-unit-tests/src/test/java/spring-queue.xml deleted file mode 100644 index 94c31a2a5c..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/spring-queue.xml +++ /dev/null @@ -1,86 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - false - - - - - - - false - - - - - - - - - - - - - - - 10 - - - - - - - - - - - - - - - - - - - org.apache.activemq.spring.Test.spring.queue - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/java/spring.xml b/tests/activemq5-unit-tests/src/test/java/spring.xml deleted file mode 100644 index 51eb08d03a..0000000000 --- a/tests/activemq5-unit-tests/src/test/java/spring.xml +++ /dev/null @@ -1,79 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 10 - - - - - - - - - - - - - - - - - - org.apache.activemq.spring.Test.spring.topic - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/resources/activemq-partition.xml b/tests/activemq5-unit-tests/src/test/resources/activemq-partition.xml deleted file mode 100644 index 4bb96f22a9..0000000000 --- a/tests/activemq5-unit-tests/src/test/resources/activemq-partition.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/resources/activemq.xml b/tests/activemq5-unit-tests/src/test/resources/activemq.xml deleted file mode 100644 index eb49ca08d0..0000000000 --- a/tests/activemq5-unit-tests/src/test/resources/activemq.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/resources/spring-embedded-xbean-bean-ref.xml b/tests/activemq5-unit-tests/src/test/resources/spring-embedded-xbean-bean-ref.xml deleted file mode 100644 index b6daf725c6..0000000000 --- a/tests/activemq5-unit-tests/src/test/resources/spring-embedded-xbean-bean-ref.xml +++ /dev/null @@ -1,101 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 10 - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/resources/spring-embedded-xbean-local.xml b/tests/activemq5-unit-tests/src/test/resources/spring-embedded-xbean-local.xml deleted file mode 100644 index 584faea2b6..0000000000 --- a/tests/activemq5-unit-tests/src/test/resources/spring-embedded-xbean-local.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 10 - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/resources/spring-embedded-xbean-noversion.xml b/tests/activemq5-unit-tests/src/test/resources/spring-embedded-xbean-noversion.xml deleted file mode 100644 index e21073c3a3..0000000000 --- a/tests/activemq5-unit-tests/src/test/resources/spring-embedded-xbean-noversion.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 10 - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/resources/spring-embedded-xbean.xml b/tests/activemq5-unit-tests/src/test/resources/spring-embedded-xbean.xml deleted file mode 100644 index e21073c3a3..0000000000 --- a/tests/activemq5-unit-tests/src/test/resources/spring-embedded-xbean.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 10 - - - - - - - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/resources/spring-embedded.xml b/tests/activemq5-unit-tests/src/test/resources/spring-embedded.xml deleted file mode 100644 index 39f09503ea..0000000000 --- a/tests/activemq5-unit-tests/src/test/resources/spring-embedded.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 10 - - - - - - - - - - - - - - - - - - org.apache.activemq.spring.Test.spring.embedded - - - - - diff --git a/tests/activemq5-unit-tests/src/test/resources/spring-jndi.xml b/tests/activemq5-unit-tests/src/test/resources/spring-jndi.xml deleted file mode 100644 index 4ad519b1d8..0000000000 --- a/tests/activemq5-unit-tests/src/test/resources/spring-jndi.xml +++ /dev/null @@ -1,119 +0,0 @@ - - - - - - - - - - - - org.apache.activemq.jndi.ActiveMQInitialContextFactory - - example.Spring.MyTopic - - - - - - - - - - - ConnectionFactory - - - - - - - - - - MyTopic - - - - - - true - - - - - - - - - - - - - - - - - - true - - - - - - - - - - - - - - - - - - - 10 - - - - - - - - - - - - - - - - - - example.Spring.MyTopic - - - - - diff --git a/tests/activemq5-unit-tests/src/test/resources/spring-queue.xml b/tests/activemq5-unit-tests/src/test/resources/spring-queue.xml deleted file mode 100644 index 94c31a2a5c..0000000000 --- a/tests/activemq5-unit-tests/src/test/resources/spring-queue.xml +++ /dev/null @@ -1,86 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - false - - - - - - - false - - - - - - - - - - - - - - - 10 - - - - - - - - - - - - - - - - - - - org.apache.activemq.spring.Test.spring.queue - - - - - - diff --git a/tests/activemq5-unit-tests/src/test/resources/spring-start-false.xml b/tests/activemq5-unit-tests/src/test/resources/spring-start-false.xml deleted file mode 100644 index 447921e40f..0000000000 --- a/tests/activemq5-unit-tests/src/test/resources/spring-start-false.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/activemq5-unit-tests/src/test/resources/spring.xml b/tests/activemq5-unit-tests/src/test/resources/spring.xml deleted file mode 100644 index 51eb08d03a..0000000000 --- a/tests/activemq5-unit-tests/src/test/resources/spring.xml +++ /dev/null @@ -1,79 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 10 - - - - - - - - - - - - - - - - - - org.apache.activemq.spring.Test.spring.topic - - - - - -